|
7 | 7 | * TreeNode(int x) { val = x; } |
8 | 8 | * } |
9 | 9 | */ |
10 | | -//Solution1: recursive dfs T: O(n) S: O(logn) |
| 10 | +//Solution1: recursive post-order T: O(n) S: O(logn) |
11 | 11 | class Solution { |
12 | 12 | public boolean hasPathSum(TreeNode root, int sum) { |
13 | | - if(root == null) return false; |
14 | | - if(root.left == null && root.right == null) return root.val == sum; |
15 | | - else return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); |
| 13 | + if (root == null) return false; |
| 14 | + return dfs(root, 0, sum); |
| 15 | + } |
| 16 | + |
| 17 | + // pathSum: current path sum, not include cur |
| 18 | + private boolean dfs(TreeNode cur, int pathSum, int sum) { |
| 19 | + if (cur == null) return false; |
| 20 | + pathSum += cur.val; |
| 21 | + if (cur.left == null && cur.right == null) { |
| 22 | + return pathSum == sum; |
| 23 | + } |
| 24 | + return dfs(cur.left, pathSum, sum) || dfs(cur.right, pathSum, sum); |
16 | 25 | } |
17 | 26 | } |
18 | 27 |
|
19 | 28 | //Solution2: iterative dfs T: O(n) S: O(n/2) |
20 | 29 | class Solution { |
21 | 30 | public boolean hasPathSum(TreeNode root, int sum) { |
22 | 31 | if (root == null) return false; |
23 | | - Stack<TreeNode> stackNode = new Stack<>(); |
24 | | - Stack<Integer> stackSum = new Stack<>(); |
25 | | - stackNode.push(root); |
26 | | - stackSum.push(root.val); |
27 | | - while (!stackNode.isEmpty()) { |
28 | | - TreeNode cur = stackNode.pop(); |
29 | | - int tmp = stackSum.pop(); |
30 | | - // Check whether it is a leaf node |
| 32 | + Stack<TreeNode> stack = new Stack<>(); |
| 33 | + Stack<Integer> sumStack = new Stack<>(); |
| 34 | + |
| 35 | + stack.push(root); |
| 36 | + sumStack.push(root.val); |
| 37 | + while (!stack.isEmpty()) { |
| 38 | + TreeNode cur = stack.pop(); |
| 39 | + int curSum = sumStack.pop(); |
31 | 40 | if (cur.left == null && cur.right == null) { |
32 | | - if (tmp == sum) return true; |
33 | | - } else { |
34 | | - if (cur.right != null) { |
35 | | - stackNode.push(cur.right); |
36 | | - stackSum.push(tmp + cur.right.val); |
37 | | - } |
38 | | - if (cur.left != null) { |
39 | | - stackNode.push(cur.left); |
40 | | - stackSum.push(tmp + cur.left.val); |
41 | | - } |
| 41 | + if (curSum == sum) return true; |
| 42 | + } |
| 43 | + if (cur.right != null) { |
| 44 | + stack.push(cur.right); |
| 45 | + sumStack.push(curSum + cur.right.val); |
| 46 | + } |
| 47 | + if (cur.left != null) { |
| 48 | + stack.push(cur.left); |
| 49 | + sumStack.push(curSum + cur.left.val); |
42 | 50 | } |
43 | 51 | } |
44 | 52 | return false; |
|
0 commit comments