Leetcode.121路径总和
深度优先
采用从上至下,将targetsum的值依次减去遍历过的每个节点的值,最后遍历到叶子节点,如果叶子节点的值等于最后这个targetsum的值,则说明这条路径存在
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root==null){
return false;
}
// 说明这个是叶子节点了
if(root.left==null&&root.right==null){
return targetsum == root.val;
}
// 递归查找
return hasPathSum(root.left,targetsum-root.val)||hasPathSum(root.right,targetsum-root.val);
}
广度优先
广度优先则采用队列,横向遍历,把每个节点的值依次相加,到叶子节点后,再比较这个值与targetsum是否相等。
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
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 temp = queVal.poll();// 当前节点的值
if (now.left == null && now.right == null) { // 找到叶子节点。判断是否符合
if (temp == sum) {
return true;
}
continue;
}
// 广度优先,**注意**:这里存的值,是上面往下面,遍历到的值得总和
if (now.left != null) {
queNode.offer(now.left);
queVal.offer(now.left.val + temp);
}
if (now.right != null) {
queNode.offer(now.right);
queVal.offer(now.right.val + temp);
}
}
return false;
}
}

浙公网安备 33010602011771号