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

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

    //method1:递归版本
    class Solution{
        public:
            vector<vector<int>> pathSum(TreeNode* root, int sum){
                vector<vector<int>> res;
                vector<int> out;
                helper(root,sum,out,res);
                return res;
            }
        
        void helper(TreeNode* node, int sum, vector<int>& out, vector<vector<int>>& res){
            if(!node) return;
            out.push_back(node->val);//1
            if(sum == node->val && !node->left && !node->right){
                res.push_back(out);
            } 
            
            helper(node->left,sum-node->val,out,res);
            helper(node->right, sum-node->val,out,res);
            out.pop_back();//由于以上1处是先把val加到vector中,如果不符合需要跳转到上一级,此处需要弹出处理;  
        }
    };
    
    
    //迭代版本
    //注意:11处要考虑最左节点不是叶子节点,下面还有一个右子节点的情况;
    //可以参看:https://www.cnblogs.com/grandyang/p/4042156.html
    class Solution{
        public:
              vector<vector<int>> pathSum(TreeNode* root, int sum){
                vector<vector<int>> res;
                vector<TreeNode*> s;
                TreeNode *cur = root,*pre = NULL;
                int val = 0;
                while(cur || !s.empty()){
                    while(cur){
                        s.push_back(cur);
                        val += cur->val;
                        cur = cur->left;
                    }
                    cur = cur->back();  
                    if(!cur->left && !cur->right && val == sum){
                        vector<int> v;
                        for(auto it : s){
                            v.push_back(it->val);
                        }
                        res.push_back(v);
                    }
                    if(cur->right && cur->right != pre) cur = cur->right;//11
                    else{
                        pre = cur;
                        val -= cur->val;
                        s.pop_back();
                        cur = NULL;
                    }
                }  
                  
                return res;
              }
    };












































    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    内向者生存手册
    不良言论屏蔽方案探讨——附加一点思考
    提高复用性的编码习惯
    如何管好.net的内存
    谨防信息超载
    .net的反对派们,精神比表面的东西更重要
    为什么我老是半途而废?
    对不起,我也是来给.Net泼冷水的(山寨版)
    把重要的事情先做好
    学英语(外语)的一个误区
  • 原文地址:https://www.cnblogs.com/hujianglang/p/11521959.html
Copyright © 2011-2022 走看看