#112. 路径总和
难度:简单
题目描述
解题思路
1、做加法
就是简单的DFS,每次遍历到叶子节点的时候,判断当前路径和是不是等于sum
public boolean hasPathSum(TreeNode root, int sum) {
return sumHelper(root,0,sum);
}
public boolean sumHelper(TreeNode root,int sum,int target) {
if(root == null)
return false;
sum += root.val;
if(root.left == null && root.right == null) { //如果到达了叶子节点
if(sum == target)
return true;
}
return sumHelper(root.left, sum, target) || sumHelper(root.right, sum, target);
}
2、做减法
也可以做减法,每次遍历到一个节点,把sum减去节点值,看到达叶子节点的时候是不是等于0,这样的话不需要辅助函数
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null)
return false;
sum -= root.val;
if(root.left == null && root.right == null) {
if(sum == 0)
return true;
}
return hasPathSum(root.left, sum) || hasPathSum(root.right, sum);
}
3、迭代解法
抄的官方题解,用两个栈,一个记录节点,一个记录值
public boolean hasPathSum2(TreeNode root, int sum) {
if (root == null)
return false;
LinkedList<TreeNode> node_stack = new LinkedList<>();
LinkedList<Integer> sum_stack = new LinkedList<>();
node_stack.add(root);
sum_stack.add(sum - root.val);
TreeNode node;
int curr_sum;
while ( !node_stack.isEmpty() ) {
node = node_stack.pollLast();
curr_sum = sum_stack.pollLast();
if ((node.right == null) && (node.left == null) && (curr_sum == 0))
return true;
if (node.right != null) {
node_stack.add(node.right);
sum_stack.add(curr_sum - node.right.val);
}
if (node.left != null) {
node_stack.add(node.left);
sum_stack.add(curr_sum - node.left.val);
}
}
return false;
}