版权声明: https://blog.csdn.net/weixin_40550726/article/details/82937186
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
返回 true
, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2
。
思路:采用回溯算法,深度优先遍历,记录下每一条路径的和,如果有符合条件的路径和则返回true,否则返回false。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(null==root){
return false;
}
List<Integer> list=new LinkedList<Integer>();//临时存储深度优先遍历结果
List<Integer> res=new LinkedList<Integer>(); //存储所有根结点到叶子结点的路径和
dfs(root,list,0,res);
for(Integer i:res){
if(i==sum){
return true;
}
}
return false;
}
public void dfs(TreeNode root, List<Integer> list,int tmp,List<Integer> res){
if(null==root){
return ;
}
list.add(root.val);
tmp+=root.val;
if(null==root.left&&null==root.right){
res.add(tmp);
}
dfs(root.left,list,tmp,res);
dfs(root.right,list,tmp,res);
tmp-=list.get(list.size()-1);
list.remove(list.size()-1);
}
}
解法二:采用递归的思想深度优先遍历二叉树,在遍历的过程中(即遍历到叶子结点时)判断这一条路径是否符合条件。推荐使用第二种解法。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum2(TreeNode root,int sum){
return hasSum(root,0,sum);
}
public boolean hasSum(TreeNode root,int tmp,int sum){
if(null==root){
return false;
}
tmp+=root.val;
if(tmp==sum&&root.left==null&&root.right==null){
return true;
}
return hasSum(root.left,tmp,sum)||hasSum(root.right,tmp,sum);
}
}