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


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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40086556/article/details/81388019