1 题目链接
https://www.nowcoder.com/exam/oj/ta?page=1&tpId=13&type=13
2 题目
3 思路 & 图解 & 代码
方案一:递归
把大问题分解成小问题
在方法中写清楚终止条件:
-
如果节点为空,则返回false
-
如果节点是叶子节点,且sum - 叶子节点.val = 0,返回true(从根节点到该叶子节点的这条路径是符合题目要求的)
如果不是以上两种情况
就需要继续遍历该节点的左子树和右子树,只要左右子树中有一个是满足条件的即可。所以最后用||
连接检查左子树和右子树的方法
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null && sum - root.val == 0) {
return true;
}
return hasPathSum(root.left, sum - root.val) ||
hasPathSum(root.right, sum - root.val);
}
}
方案二:Stack
我认为方案二更容易理解
栈:后进先出
-
栈是一种支持在表尾进行插入和删除操作的线性表,这一段被称为栈顶,另一端被称为栈底。
-
元素入栈指的是把新元素放到放到栈顶元素的上面,使之成为新的栈顶元素
-
元素出栈指的是从一个栈删除元素又称作出栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素
深度优先搜索(dfs):
深度优先搜索一般用于树或者图的遍历,其他有分支的(如二维矩阵)也适用。它的原理是从初始点开始,一直沿着同一分支遍历,直到该分支结束,然后回溯到上一级继续沿着一个分支走到底,如此往复,直到所有的节点都有被访问到。
准备两个stack:
-
一个用来记录当前节点
-
另一个用来记录从根节点开始,到当前节点为止,所有节点的和
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
public boolean hasPathSum(TreeNode root, int sum) {
// write code here
if (root == null) {
return false;
}
//s1用来记录节点
Stack<TreeNode> s1 = new Stack<>();
//s2用来记录到当前节点的加和
Stack<Integer> s2 = new Stack<>();
s1.push(root);
s2.push(root.val);
while (!s1.isEmpty()) {
TreeNode currentNode = s1.pop();
Integer currentSum = s2.pop();
if (currentNode.left == null && currentNode.right == null && currentSum == sum) {
return true;
}
if (currentNode.left != null) {
s1.push(currentNode.left);
s2.push(currentSum + currentNode.left.val);
}
if (currentNode.right != null) {
s1.push(currentNode.right);
s2.push(currentSum + currentNode.right.val);
}
}
return false;
}
}