
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: the root of tree
* @return: the max node
*/
public TreeNode maxNode(TreeNode root) {
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;
}
}
这个方法递归的终止条件是找到叶子结点,然后将叶子结点返回,与其根节点对比值的大小,将较大的值赋值给根节点,继续返回该根节点向上比较。返回节点中的val的确是最大数值,但返回的节点地址不是最大节点地址,且部分二叉树节点中的数值被改变,函数执行完原二叉树变了。
留言