- Path Sum:题目链接
DFS-递归
首先子问题
看左子树是否包含从root到叶子结点和为sum的路径 hasPathSum(root.left, sum - root.val)
,再看右子树是否包含hasPathSum(root.right, sum - root.val)
; 只要左子树或右子树一个包含说明有这样的路径,递归结束的条件有两个 root == null
树空 ,root.left ==null && root.right == null 返回 root.val == sum
是叶子结点
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Solution { 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); } }
|
BFS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) { return false; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode front = queue.poll(); if (front.left == null && front.right == null) { if (front.val == sum) { return true; } } if (front.left != null) { front.left.val += front.val; queue.offer(front.left); } if (front.right != null) { front.right.val += front.val; queue.offer(front.right); } } return false; } }
|