632. 二叉树的最大节点

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;
        }
    }
}
posted @ 2019-04-02 22:49  故人叹  阅读(145)  评论(0)    收藏  举报