码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Path Sum - 树的根节点到叶节点的数字之和

时间:2015-10-02 00:20:20      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:

1、题目名称

Path Sum(树的根节点到叶节点的数字之和)

2、题目地址

https://leetcode.com/problems/path-sum/

3、题目内容

英文:Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

中文:给定一颗二叉树,如果从根节点到某一叶节点的路径上数字之和等于指定的数字,返回真,否则返回假。

例如:给定数字22,树的结构为

              5
             /             4   8
           /   /           11  13  4
         /  \              7    2      1

可以找到路径5->4->11->2,使5+4+11+2=22,因此返回真

4、解题方法

本题可以使用递归,通过深度优先搜索(DFS)的方法解决。Java代码如下:

/**
 * @功能说明:LeetCode 112 - Path Sum
 * @开发人员:Tsybius2014
 * @开发时间:2015年10月1日
 */
public class Solution {
    
    /**
     * 检查一棵树中,是否有一条路让根节点到叶节点各节点值之和为指定数字
     * @param root 树的根节点
     * @param sum 指定数字
     * @return true:有这样的路;false:没有这样的路
     */
    public boolean hasPathSum(TreeNode root, int sum) {
        
        if (root == null) {
            return false;
        }
        
        if (root.left == null && root.right == null) {
            //叶节点的情况
            if (root.val == sum) {
                return true;
            } else {
                return false;
            }
        } else { 
            //非叶节点的情况
            return hasPathSum(root.left, sum - root.val) || 
                hasPathSum(root.right, sum - root.val);
        }
    }
}

END

LeetCode:Path Sum - 树的根节点到叶节点的数字之和

标签:

原文地址:http://my.oschina.net/Tsybius2014/blog/513144

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!