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

一、题目名称java

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

二、题目地址递归

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

三、题目内容开发

英文: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.get

中文:给定一颗二叉树,若是从根节点到某一叶节点的路径上数字之和等于指定的数字,返回真,不然返回假。io

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

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

能够找到路径5->4->11->2,使5+4+11+2=22,所以返回真二叉树

四、解题方法搜索

本题能够使用递归,经过深度优先搜索(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

相关文章
相关标签/搜索