题目要求大体如下:
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
大体的意思就是给一个数字,要求你给出该二叉树中从根节点到叶子所有符合路过的结点值和为该数字的路径集。
一.我的解法
因为是从根节点到叶子,所以想到的是用DFS的解法加回溯,即从根节点到叶子的路径都遍历一遍,将符合的路径加入列表中。时间复杂度是O(n)。
class Solution {
List<List<Integer>> res=new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if(root==null) return new ArrayList<>();
List<Integer> ls=new ArrayList<>();
dfs(ls,root,sum);
return res;
}
public void dfs(List<Integer> ls,TreeNode node,int sum){
ls.add(node.val);
if(node.left==null&&node.right==null)
{
if(sum==node.val)
{
res.add(new ArrayList<Integer>(ls));
}
ls.remove(ls.size()-1);
return;
}
if(node.left!=null)
dfs(ls,node.left,sum-node.val);
if(node.right!=null)
dfs(ls,node.right,sum-node.val);
ls.remove(ls.size()-1);
}
}
二.扩展
因为是采用递归的方法,就很容易想到能不能用迭代的方法实现。然后试了一下,发现总是NA,后来参考了discussion板块的别人的解法后,我才知道了在回溯的时候要检查下一结点是否是之前遍历过的。时间复杂度O(n)。
这是原地址:
https://discuss.leetcode.com/topic/31698/java-solution-iterative-and-recursive/6
class Solution{
public List<List<Integer>> pathSum(TreeNode root,int sum){
List<List<Integer>> res=new ArrayList<>();
if(root==null) return res;
List<Integer> ls=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
TreeNode pre=null;
int valsum=0;
while(cur!=null||!stack.isEmpty())
{
while(cur!=null)
{
stack.push(cur);
ls.add(cur.val);
valsum+=cur.val;
cur=cur.left;
}
cur=stack.peek();
if(cur.right!=null&&cur.right!=pre)
{
cur=cur.right;
continue;
}
if(cur.left==null&&cur.right==null&&valsum==sum)
res.add(new ArrayList<Integer>(ls));
stack.pop();
valsum-=cur.val;
ls.remove(ls.size()-1);
pre=cur;
cur=null;
}
return res;
}
}
如果有什么错误或者是可以改进的地方,请大家积极指出,我会认真改进的。