在二叉树中寻找值最大的节点并返回。
样例
给出如下一棵二叉树:
1
/ \
-5 2
/ \ / \
0 3 -4 -5
返回值为 3
的节点。
public class Solution {
/**
* @param root the root of binary tree
* @return the max ndoe
*/
/*
定义一个新的节点a,令其值为一个非常小的数,利用前序遍历比较给定节点与a的值,若给定节点比a的值大,则把此节点赋值给a,直至遍历完所有节点,返回的a即为最大节点.
*/
//需要在外面定义结点
TreeNode max = new TreeNode(-10000000);
public TreeNode maxNode(TreeNode root) {
// Write your code here
if(root == null)return null;
if(root.val>max.val){
max.val = root.val;
maxNode(root.left);
maxNode(root.right);
}
return max;
}
}