题目:
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22
,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
返回 true
, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2
。
思路:好像关于树的题目都可以使用递推来完成。本题也是。基本的思路就是遍历根节点到叶子节点所有的路径,判断是否和给定的值相等。
这个题我自己试着又做了,但是还是不能再20分钟里面做出来。我自己想的是用非递归的思想做,就是用深度优先搜索的方式,但是不知道回退的时候总和应该怎么算。之后看了解析后发现可以简单的使用递推来写。。。。。。。
以下的代码1是我在官方题解中找到的关于深度递归的写法,对于回退的和,是使用一个栈来保存遍历到当前节点时,从根节点到此时的和。
代码1:
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
LinkedList<TreeNode> node_stack = new LinkedList();
LinkedList<Integer> sum_stack = new LinkedList();
node_stack.add(root);
sum_stack.add(sum - root.val);
TreeNode node;
int curr_sum;
while ( !node_stack.isEmpty() ) {
node = node_stack.pollLast();
curr_sum = sum_stack.pollLast();
if ((node.right == null) && (node.left == null) && (curr_sum == 0))
return true;
if (node.right != null) {
node_stack.add(node.right);
sum_stack.add(curr_sum - node.right.val);
}
if (node.left != null) {
node_stack.add(node.left);
sum_stack.add(curr_sum - node.left.val);
}
}
return false;
}
}
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root==null)
return false;
else if(root.left==null&&root.right==null&&root.val==sum)
return true;
else
{
return hasPathSum(root.left,sum-root.val)||hasPathSum(root.right,sum-root.val);
}
}
}
执行用例最快的代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
if (root.left == null && root.right == null) return sum == root.val;
if (root.left == null) return hasPathSum(root.right, sum-root.val);
if (root.right == null) return hasPathSum(root.left, sum-root.val);
return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
}
}