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

    通过一个p指针,遍历 二叉树,并将每次的值 保存在 sum2 中 。

    遇到右节点,将右节点+depth 保存在 temp中,当再次使用 该节点时,根据depth 将sum2中的长度削减成 depth-1

    /**
     * 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>> re;
            if(root==NULL) return re;
            TreeNode *p=root; int depth=1;
            vector<pair<TreeNode * ,int>>  temp;             // 保存右节点+depth
            vector<int> sum2;                                // 保存一条路径的所有点值
            pair<TreeNode *, int > t=make_pair(root,depth);  
           // temp.push_back(t);
            while(!temp.empty()||p!=NULL){
                sum2.push_back(p->val);
                if(p->left!=NULL){
                    if(p->right!=NULL){
                        temp.push_back(make_pair(p->right,depth+1));  
                    }
                    p=p->left;
                    depth++;
                }
                else{
                    if(p->right==NULL){
                        int result=0;
                        for(int i=0;i<sum2.size();i++)
                        {
                            result=result+sum2[i];
                        }
                        if(result==sum)
                            re.push_back(sum2);
                        if(temp.empty()) break;
                        p=(*(temp.end()-1)).first;
                        depth=(*(temp.end()-1)).second;
                        temp.erase(temp.end()-1);
                        sum2.erase(sum2.begin()+depth-1,sum2.end());
                    }
                    else{
                    p=p->right;
                    depth++;                   
                    }
                }                
            }
            return re;
        }
    };
  • 相关阅读:
    [hadoop](2) MapReducer:Distributed Cache
    [hadoop](1) MapReduce:ChainMapper
    hadoop平台搭建
    postgresql主从同步配置
    问题记录-java图片验证码显示乱码
    windows mongodb启动
    新的开始
    springboot和Redis整合
    springboot的简单热部署
    springmvc模式下的上传和下载
  • 原文地址:https://www.cnblogs.com/NeilZhang/p/5499438.html
Copyright © 2011-2022 走看看