Path Sum

来源:互联网 发布:topsurv怎么连接网络 编辑:程序博客网 时间:2024/05/11 22:27

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.

For example:
Given the below binary tree and sum = 22,
              5             / \            4   8           /   / \          11  13  4         /  \      \        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

Show Tags
 Tree Depth-first Search

Have you met this question in a real interview?

思路:还是树的递归问题,把握好递归的结束条件,这种题还是很有规律的

代码如下:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    private boolean flag = false;    public boolean hasPathSum(TreeNode root, int sum) {        dfs(root,sum,0);        return flag;    }        public void dfs(TreeNode root,int sum,int cur){        if(root==null) {             return;        }else{           cur = cur+root.val;           //保证已经到达叶子节点,是一条完整的路径           if(cur==sum && root.right==null &root.left==null){             flag = true;           }        }              dfs(root.left,sum,cur);        dfs(root.right,sum,cur);    }}


0 0
原创粉丝点击