主题思想: 递归回溯, 关键点在于什么时候选择回溯,什么时候应该结束。
当遇到null 时结束,则应该在遍历完一个节点的左右子树过后,再删除栈顶元素。
AC 代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ans=new ArrayList<List<Integer>>();
if(root==null) return ans;
findPath(root,new ArrayList<Integer>(), ans,0,sum);
return ans;
}
public void findPath(TreeNode root, List<Integer> tmpList,List<List<Integer>> ans,int tmp,int sum){
if(root==null) return ;
tmpList.add(root.val);
if(root.left==null&&root.right==null){
if(tmp+root.val==sum){
ans.add(new ArrayList<Integer>(tmpList));
}
}
findPath(root.left,tmpList,ans,tmp+root.val,sum);
findPath(root.right,tmpList,ans,tmp+root.val,sum);
//here is important
tmpList.remove(tmpList.size()-1);
}
}
本文介绍了一种使用递归回溯算法解决寻找二叉树中所有和为特定值的路径的问题。通过深入剖析递归回溯的关键点,即何时进行回溯以及何时结束搜索,给出了解决该问题的AC代码实现。
965

被折叠的 条评论
为什么被折叠?



