題目
描述
在二叉樹(shù)中尋找值最大的節(jié)點(diǎn)并返回巧娱。
樣例
給出如下一棵二叉樹(shù):
1
/ \
-5 2
/ \ / \
0 3 -4 -5
返回值為 3 的節(jié)點(diǎn)。
解答
思路
遞歸遍歷
代碼
public class Solution {
/**
* @param root the root of binary tree
* @return the max ndoe
*/
public TreeNode maxNode(TreeNode root) {
// Write your code here
if(root == null) return null;
TreeNode left = root;
TreeNode right = root;
if(root.left != null)
left = maxNode(root.left);
if(root.right != null)
right = maxNode(root.right);
if(left.val > root.val)
root.val = left.val;
if(right.val > root.val)
root.val = right.val;
return root;
}
}