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)
  • 相关阅读:
    Benelux Algorithm Programming Contest 2016 Preliminary K. Translators’ Dinner(思路)
    Benelux Algorithm Programming Contest 2016 Preliminary Target Practice
    Benelux Algorithm Programming Contest 2016 Preliminary I. Rock Band
    Benelux Algorithm Programming Contest 2016 Preliminary A. Block Game
    ICPC Northeastern European Regional Contest 2019 Apprentice Learning Trajectory
    ICPC Northeastern European Regional Contest 2019 Key Storage
    2018 ACM ICPC Asia Regional
    2018 ACM ICPC Asia Regional
    Mybatis入库出现异常后,如何捕捉异常
    优雅停止 SpringBoot 服务,拒绝 kill -9 暴力停止
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10093284.html
Copyright © 2011-2022 走看看