首页 > 其他 > 详细

632. 二叉树的最大节点

时间:2019-04-02 23:07:23      阅读:132      评论:0      收藏:0      [点我收藏+]

Description

Find the maximum node in a binary tree, return the node.

Example

Given a binary tree:

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

return the node with value 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
     */
    public TreeNode maxNode(TreeNode root) {
        // write your code here
        TreeNode max = root;
        TreeNode leftMaxNode = null;
        TreeNode rightMaxNode = null;
        if (root == null){
            return null;
        }
        if (root.left != null){
            leftMaxNode = maxNode(root.left);
            if (leftMaxNode.val > max.val){
                max = leftMaxNode;
            }
        }
        if (root.right != null){
            rightMaxNode = maxNode(root.right);
            if (rightMaxNode.val > max.val){
                max = rightMaxNode;
            }
        }
        return max;
    }
}
public class Solution {
    /*
     * @param root: the root of tree
     * @return: the max node
     */
    public TreeNode maxNode(TreeNode root) {
        // write your code here
        if (root==null) return null;
        return max(root, max(maxNode(root.left), maxNode(root.right)));
    }

    private TreeNode max(TreeNode t1, TreeNode t2){
        if (t1 == null && t2 == null) return null;
        if (t1 == null && t2 != null) return t2;
        if (t1 != null && t2 == null) return t1;
        if (t1.val>t2.val){
            return t1;
        }else {
            return t2;
        }
    }
}

632. 二叉树的最大节点

原文:https://www.cnblogs.com/browselife/p/10646006.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!