leetcode_深度优先算法

题目:

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

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例: 
给定如下二叉树,以及目标和 sum = 22,

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

solution:

class Solution {
    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;
            return false;
        
        }
        boolean result = true;
        result = hasPathSum(root.left,sum-root.val);
        if(result==true){
            return result;
        }
        result = hasPathSum(root.right,sum-root.val);
        if(result==true){
            return result;
        }
        return false;
        
    }
}
 


 

发布了640 篇原创文章 · 获赞 12 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/xiamaocheng/article/details/104978880