LintCode-632. 二叉树的最大节点

题目

描述

在二叉树中寻找值最大的节点并返回。

样例

给出如下一棵二叉树:

     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
        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;
    }
}

你可能感兴趣的:(LintCode-632. 二叉树的最大节点)