112. 路径总和
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2。
利用树的层次遍历(BFS),运用两个队列,一个放节点,一个放路径所到当前的节点的路径和
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null)
return false;
Queue<TreeNode>nodeq = new LinkedList<TreeNode>();
Queue<Integer>valq = new LinkedList<Integer>();//所经过路径上每个节点的和
nodeq.offer(root);
valq.offer(root.val);
while(!nodeq.isEmpty()){
TreeNode tnode = nodeq.poll();
int tval = valq.poll();
if(tval == sum && tnode.left == null && tnode.right == null)
return true;
if(tnode.left != null){
nodeq.offer(tnode.left);
valq.offer(tnode.left.val + tval);
}
if(tnode.right != null){
nodeq.offer(tnode.right);
valq.offer(tnode.right.val + tval);
}
}
return false;
}
递归法:省时省内存
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null)
return false;
if(root.left == null && root.right == null)
return root.val == sum;
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}