zoukankan      html  css  js  c++  java
  • 113. 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.

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

    Approach #1: C++. [Recursive]

    /**
     * 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) {
            if (root == NULL) return ans;
            vector<int> temp;
            helper(root, temp, 0, sum);
            return ans;
        }
    private:
        vector<vector<int>> ans;
        
        void helper(TreeNode* root, vector<int> temp, int cur, int sum) {  
            if (root == NULL) return;
            temp.push_back(root->val);
            if (root->left == NULL && root->right == NULL && cur+root->val == sum) {
                ans.push_back(temp);
                return;
            }
            helper(root->left, temp, cur+root->val, sum);
            helper(root->right, temp, cur+root->val, sum);
        }
    };
    

      

    Approach #2: Java.[DFS+Stack]

    /**
     * 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>> res = new ArrayList<>();
            List<Integer> path = new ArrayList<>();
            Stack<TreeNode> stack = new Stack<>();
            int curSum = 0;
            TreeNode cur = root;
            TreeNode prev = null;
            while (cur != null || !stack.isEmpty()) {
                while (cur != null) {
                    stack.push(cur);
                    curSum += cur.val;
                    path.add(cur.val);
                    cur = cur.left;
                }
                cur = stack.peek();
                if (cur.right != null & cur.right != prev) {
                    cur = cur.right;
                    continue;
                }
                if (cur.left == null && cur.right == null && curSum == sum)
                    res.add(new ArrayList<Integer>(path));
                prev = cur;
                stack.pop();
                path.remove(path.size()-1);
                curSum -= cur.val;
                cur = null;
            }
            return res;
        }
    }
    

      

    Approach #3: Python. [BFS+Queue]

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def pathSum(self, root, sum):
            """
            :type root: TreeNode
            :type sum: int
            :rtype: List[List[int]]
            """
            if root == None:
                return []
            
            res = []
            
            queue = [(root, root.val, [root.val])]
            
            while queue:
                curr, val, ls = queue.pop()
                
                if not curr.left and not curr.right and val == sum:
                    res.append(ls)
                if curr.left:
                    queue.append((curr.left, val+curr.left.val, ls+[curr.left.val]))
                if curr.right:
                    queue.append((curr.right, val+curr.right.val, ls+[curr.right.val]))
                    
            return res
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    PAT (Advanced Level) Practice 1100 Mars Numbers (20分)
    PAT (Advanced Level) Practice 1107 Social Clusters (30分) (并查集)
    PAT (Advanced Level) Practice 1105 Spiral Matrix (25分)
    PAT (Advanced Level) Practice 1104 Sum of Number Segments (20分)
    PAT (Advanced Level) Practice 1111 Online Map (30分) (两次迪杰斯特拉混合)
    PAT (Advanced Level) Practice 1110 Complete Binary Tree (25分) (完全二叉树的判断+分享致命婴幼儿错误)
    PAT (Advanced Level) Practice 1109 Group Photo (25分)
    PAT (Advanced Level) Practice 1108 Finding Average (20分)
    P6225 [eJOI2019]异或橙子 树状数组 异或 位运算
    P4124 [CQOI2016]手机号码 数位DP
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10093284.html
Copyright © 2011-2022 走看看