Binary Tree Maximum Node
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 public class Solution { 2 /** 3 * @param root the root of binary tree 4 * @return the max ndoe 5 */ 6 public TreeNode maxNode(TreeNode root) { 7 // Write your code here 8 if(root == null) return root; 9 TreeNode leftMax = null; 10 if(root.left!=null){ 11 leftMax = maxNode(root.left); 12 } 13 TreeNode rightMax = null; 14 if(root.right!=null){ 15 rightMax = maxNode(root.right); 16 } 17 TreeNode max = root; 18 if(leftMax!=null){ 19 max = leftMax.val>max.val? leftMax : max; 20 } 21 if(rightMax!=null){ 22 max = rightMax.val>max.val? rightMax : max; 23 } 24 return max; 25 } 26 }