LintCode-(632)二叉树的最大节点

来源:互联网 发布:linux daemonize 编辑:程序博客网 时间:2024/06/15 00:20

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


样例

给出如下一棵二叉树:

     1   /   \ -5     2 / \   /  \0   3 -4  -5 

返回值为 3 的节点。


/** * 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     */     //先给max赋一个极小值    TreeNode max=new TreeNode(Integer.MIN_VALUE);    public TreeNode maxNode(TreeNode root) {        // write your code here         //判断二叉树是否为空    if(root==null)       return null;    //递归算法,每次都将最大结点赋给max    max=max.val>root.val?max:root;    maxNode(root.left);    maxNode(root.right);    return max;    }}



原创粉丝点击