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)
  • 相关阅读:
    POJ 1611 The Suspects(并查集)
    POJ 2485 Highways(最小生成树Prim算法)
    POJ 1062 昂贵的聘礼(最短路径Dijkstr的变形)
    SDUT 2374 || HDU 1803Cylinder(计算几何求体积)
    HDU 1804 || SDUT 2375 Deli Deli(简单题)
    POJ 3041 Asteroids(二分图的最大匹配)
    HDU 1802 || SDUT 2373 Black and white painting(规律)
    POJ 1035 Spell checker(字符串简单匹配)
    POJ 3080 Blue Jeans(KMP模式匹配)
    js中反斜杠\的一些研究
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10093284.html
Copyright © 2011-2022 走看看