Path Sum II

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]
]

第一题比较的话,不再仅仅追求是否存在这样的路径,而是要求得到所有符合条件的路径,那么我们就要保存这些路径,该怎么保存这样的路径呢。开始考虑采用迭代的方式,这样就可以采用全局变量来存储符合条件的路径,但是感觉也不好求(主要是自己不擅长将一个递归转换成迭代方式,每一次转换,都是错误百出,要调试多次,才能转换妥当,不过记得在一道题说,递归在实际中是不用的),所以就使用list,由于list是对象,而在函数之间传递对象时使用对象的地址传递,故也就起到了全局变量的作用。因此有了下面的算法。思路还是很简单的,不过在处理path的处理,在inorder里添加了一个节点,递归到上一个节点时还需要删除这个节点(由于path是一个"全局变量",会影响在其他函数中的使用),只要处理好了add和remove的时刻就OK了,其他的就是一个DFS过程。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> list = new ArrayList<List<Integer>>();//用来记录全局结果
        List<TreeNode> path = new ArrayList<TreeNode>();//记录走过的路径
        if(root != null){
            inorder(root,list,path,0,sum);
        }
        return list;
    }
    public void inorder(TreeNode root,List<List<Integer>> list,List<TreeNode> path,int value , int sum){
        if(root.left == null && root.right == null){//叶子节点
            if(root.val + value == sum){//找到了,复制路径,此时path里都是符合题意的节点
                List<Integer> tmp = new ArrayList<Integer>();
                for(int i =0; i < path.size();i++){
                    tmp.add(path.get(i).val);
                }
                tmp.add(root.val);
                list.add(tmp);
            }
        }else{//非叶子节点
            boolean flag = false;
            if(root.left != null){
                path.add(root);
                inorder(root.left,list,path,value+root.val,sum);
                flag = true;
            }
            if(root.right != null){
                if(flag){//true,说明root在路径里,不重复添加
                    inorder(root.right,list,path,value+root.val,sum);
                }else{//root不在路径里
                    path.add(root);
                    inorder(root.right,list,path,value+root.val,sum);
                }
            }
            path.remove(root);
        }
    }
}

Runtime: 284 ms

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值