思路:
对于二叉树的一条合适路径的选择,直接使用DFS,但是这道题在调试的时候还是遇到了小麻烦,
注意点:
1. base case 的中断条件是 左右子节点都为空,叶子结点返回
2. 值进行和目标值对比
遇到的难点:
没分析清楚叶子节点 ,直接 root == null进行了比较;叶子结点是重要点
结果:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
//DFS 直接深度搜索遍历
if(root == null){
return false;
}
return DFS(root,targetSum,0);
}
public boolean DFS(TreeNode root, int targetSum,int sum){
if (root == null) {
return false;
} else if (root.left == null && root.right == null) {
if (targetSum == sum + root.val) {
return true;
} else {
return false;
}
}
boolean ans = DFS(root.left,targetSum,sum+root.val)
|| DFS(root.right,targetSum,sum+root.val);
return ans;
}
}
其他题解:
1.利用 sum-root.val 最后求得结果相等,有点那个从链表中找是否存在满足target的值的思路;利用的也是 target - value ;DFS就是递归
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return sum == root.val;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}
2.BFS
两个队列同步表示此位置的值的和为多少
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;
}
}
总结:
一点一点积累,总会会的