112.路径总和
方法:广度优先搜索
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null){
return false;
}
Queue<TreeNode> queNode = new LinkedList<TreeNode>();
Queue<Integer> queVal = new LinkedList<Integer>();
queNode.offer(root);
queVal.offer(root.val);
while(!queNode.isEmpty()){
TreeNode now = queNode.poll();
int tmp = queVal.poll();
if(now.left == null && now.right == null){
if(tmp == targetSum){
return true;
}
continue;
}
if(now.left!= null){
queNode.offer(now.left);
queVal.offer(now.left.val+tmp);
}
if(now.right!=null){
queNode.offer(now.right);
queVal.offer(now.right.val + tmp);
}
}
return false;
}
}