zoukankan      html  css  js  c++  java
  • 输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。中的pop讲解。

    /*
    struct TreeNode {
    	int val;
    	struct TreeNode *left;
    	struct TreeNode *right;
    	TreeNode(int x) :
    			val(x), left(NULL), right(NULL) {
    	}
    };*/
    #include<vector>
    #include<algorithm>
    class Solution {
    public:
        vector<vector<int>>res;
        vector<int>buffer;
        static bool cmp( const vector<int> &a, const vector<int> &b)
        {
    	return a.size() > b.size();
        }
        vector<vector<int> > FindPath1(TreeNode* root,int expectNumber)
        {
            if(root == NULL)return res;
            buffer.push_back(root->val);
            if(expectNumber-root->val == 0 && root->left ==NULL && root->right == NULL)
            {
                res.push_back(buffer);
            }
            if(root->left != NULL)FindPath(root->left,expectNumber-root->val);
            if(root->right !=NULL)FindPath(root->right,expectNumber-root->val);
            if(buffer.size()!=0)
            buffer.pop_back();//每次压进来多少,就弹出去多少。
            //if(res.size() != 0)
            return res;
        }
        vector<vector<int> > FindPath(TreeNode* root,int expectNumber)
        {
            FindPath1(root,expectNumber);//这个子函数是为了进行筛选出来这些路径
    	    sort(res.begin(), res.end(), cmp);//这个函数是为了对给出的路径进行排序
            return res;
        }
    };
    

     

     每一个递归函数的结束,就会把这个节点弹出去,然后将这个节点的父节点的右孩子节点进行压入。

    直到再一次到达端点,然后再进行重新的一次弹出。大家直接看图把,上面都标着序号呢。

  • 相关阅读:
    Redis基础
    Windows 10 中 安装 RabbitMQ
    Nginx
    第二章-矩阵
    第一章-行列式
    第六章-微分方程
    第五章-多元函数
    第四章-定积分
    第三章-不定积分
    第二章-导数
  • 原文地址:https://www.cnblogs.com/littleswan/p/12706430.html
Copyright © 2011-2022 走看看