Find the maximum node in a binary tree, return the node.
樣例
給出如下一棵二叉樹:
1
/
-5 2
/ \ /
0 3 -4 -5
返回值為 3 的節點。
分析
簡單的遞歸思路,不過注意為空的情況,所以最好將為空的點的值設為最小值
代碼
public class Solution {
/**
* @param root the root of binary tree
* @return the max ndoe
*/
public TreeNode maxNode(TreeNode root) {
if(root == null)
return null;
return getMaxNode(root);
}
public TreeNode getMaxNode(TreeNode root) {
if(root == null)
return new TreeNode(Integer.MIN_VALUE);
TreeNode left = getMaxNode(root.left);
TreeNode right = getMaxNode(root.right);
if(root.val >= right.val && root.val >= left.val)
return root;
if(left.val >= right.val && left.val >= root.val)
return left;
return right;
}
}