Lintcode:二叉樹的最大節點
阿新 • • 發佈:2019-02-04
在二叉樹中尋找值最大的節點並返回。
樣例
給出如下一棵二叉樹:
1
/ \
-5 2
/ \ / \
0 3 -4 -5
返回值為 3
的節點。
python:
class Solution: """ @param: root: the root of tree @return: the max node """ def maxNode(self, root): # write your code here if root is None: return self.max(root) return self.node maxVal = -9999 node = None def max(self, root): if root is None: return if root.val >= self.maxVal: self.maxVal = root.val self.node = root self.max(root.left) self.max(root.right)
C++:
class Solution { public: /* * @param root: the root of tree * @return: the max node */ int maxx=-99999; TreeNode *pmax; void max(TreeNode *root) { if(root==NULL) return ; if(root->val>maxx) { maxx=root->val; pmax=root; } max(root->left); max(root->right); } TreeNode * maxNode(TreeNode * root) { // write your code here if(root==NULL) return NULL; max(root); return pmax; } };