描述:
在二叉树中寻找值最大的节点并返回。
样例;
给出如下一棵二叉树:
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) {
// Write your code here
ArrayList<TreeNode> result = new ArrayList<TreeNode>();
result.add(root);
search(root , result);
return result.get(0);
}
public void search(TreeNode root , ArrayList<TreeNode> result){
if(root == null){
return ;
}
if(result.get(0).val < root.val){
result.set(0 , root);
}
if(root.left != null){
search(root.left , result);
}
if(root.right != null){
search(root.right , result);
}
}
}