存储路径:递归或者是DFSleetcode113. Path Sum II路径之和II递归DFS

9 篇文章 0 订阅
3 篇文章 0 订阅

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

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]
]
 
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>>res;
        vector<int> temp;
        helper(root,sum,res,temp);
        return res;
        
    }
/*试试剪枝效率,也就是当当前sum<0,就停止继续下去,返回*/
    void helper(TreeNode *root,int sum,vector<vector<int>>&res,vector<int>&temp)
    {
        if(root==NULL)
            return;
        temp.push_back(root->val);
         if(!root->left&&!root->right&&sum-root->val==0)
                res.push_back(temp);
        helper(root->left,sum-root->val,res,temp);
         helper(root->right,sum-root->val,res,temp);

/*在经历过左右结点遍历之后,也就是说到达最后的叶子节点,可以说是一条路径已经完成任务了,
不管是否这条路径之和为sum,我们都要改换下一条路径,那么我们就要把这个叶子节点pop出来,
此时temp里没有当前叶子节点,而程序执行到最后,
回溯到上一位置,之后从父亲节点的右子树开始从新进行迭代,
从而不断更新temp,直至该右子树所有路径都已遍历完成*/

        temp.pop_back();


    }
};

迭代法 

public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        int SUM = 0;
        TreeNode cur = root;
        TreeNode pre = null;
        while(cur!=null || !stack.isEmpty()){
            while(cur!=null){
                stack.push(cur);
                path.add(cur.val);
                SUM+=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 && SUM==sum) 
                res.add(new ArrayList<Integer>(path));
  
            pre = cur;
            stack.pop();
            path.remove(path.size()-1);
            SUM-=cur.val;
            cur = null;
        
        }
        return res;
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值