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

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

难度:普通
要求:

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

样例:

给出如下一棵二叉树:

     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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 树的概述 树是一种非常常用的数据结构,树与前面介绍的线性表,栈,队列等线性结构不同,树是一种非线性结构 1.树的定...
    Jack921阅读 4,489评论 1 31
  • 1 序 2016年6月25日夜,帝都,天下着大雨,拖着行李箱和同学在校门口照了最后一张合照,搬离寝室打车去了提前租...
    RichardJieChen阅读 5,154评论 0 12
  • 基于树实现的数据结构,具有两个核心特征: 逻辑结构:数据元素之间具有层次关系; 数据运算:操作方法具有Log级的平...
    yhthu阅读 4,315评论 1 5
  • 版权声明:本文为博主原创文章,未经博主允许不得转载。 难度:普通 要求: 给定一个二叉树,找出所有路径中各节点相加...
    柒黍阅读 314评论 0 0
  • 去年二叉树算法的事情闹的沸沸扬扬,起因是Homebrew 的作者 @Max Howell 在 twitter 上发...
    Masazumi柒阅读 1,627评论 0 8