632. Binary Tree Maximum Node【Naive】
Find the maximum node in a binary tree, return the node.
Example
Given a binary tree:
1
/ \
-5 2
/ \ / \
0 3 -4 -5
return the node with value 3
.
解法一:
1 class Solution { 2 public: 3 /** 4 * @param root the root of binary tree 5 * @return the max node 6 */ 7 TreeNode* maxNode(TreeNode* root) { 8 // Write your code here 9 if (root == NULL) { 10 return root; 11 } 12 13 TreeNode* left = maxNode(root->left); 14 TreeNode* right = maxNode(root->right); 15 16 return max(root, max(left, right)); 17 } 18 19 TreeNode* max(TreeNode* a, TreeNode* b) { 20 if (a == NULL || b == NULL) { 21 return (a == NULL ? b : a); 22 } 23 24 return (a->val > b->val ? a : b); 25 } 26 27 28 };
posted on 2018-02-03 15:44 LastBattle 阅读(185) 评论(0) 编辑 收藏 举报