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

2017-09-16  本文已影响0人  柒黍

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:普通
要求:

给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。
一个有效的路径,指的是从根节点到叶节点的路径。

样例:

给出如下一棵二叉树:

     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 binary tree
     * @return the max ndoe
     */
    public TreeNode maxNode(TreeNode root) {
        // Write your code here
        return getMaxNode(root);
    }
    
    
    private TreeNode getMaxNode(TreeNode node){
        if(node == null){
            return node;
        }    
    
        TreeNode maxLeft = getMaxNode(node.left);
        TreeNode maxRight = getMaxNode(node.right);
        
        if(maxLeft != null && maxRight != null){
            TreeNode max = maxLeft.val > maxRight.val ? maxLeft : maxRight;
            return node.val > max.val ? node : max;
        } else {
            if(maxLeft != null){
                return node.val > maxLeft.val ? node : maxLeft;
            }
            if(maxRight != null){
                return node.val > maxRight.val ? node : maxRight;
            }
        }
        return node;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读