zoukankan      html  css  js  c++  java
  • 剑指offer23-二叉树中和为某一值的路径

    输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

    思路:dfs

        vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
            vector<vector<int> >res;
            vector<int> path;
            if(root==NULL||expectNumber==0) return res;
            Find(root,expectNumber,res,path);
            return res;
        }
        void Find(TreeNode*root,int expect,vector<vector<int> >&res,vector<int>&path)
        {
            
            path.push_back(root->val);
            if(root->left==NULL&&root->right==NULL)
            {
                int temp_pathSum=0;
                for(int i=0;i<path.size();i++)
                {
                    temp_pathSum+=path[i];
                }
                if(temp_pathSum==expect)
                {
                    res.push_back(path);
                }
            }
            
            if(root->left!=NULL)
                Find(root->left,expect,res,path);
            if(root->right!=NULL)
                Find(root->right,expect,res,path);
            path.pop_back();
        }

  • 相关阅读:
    ReentrantLock重入锁
    Java对象序列化和反序列
    echarts踩坑笔记
    金融风控之贷款违约预测笔记
    go安装模块
    vasp计算轨道吸附
    html
    css/js 小技巧
    python 调用父类方法:super && 直接使用父类名
    python 多线程
  • 原文地址:https://www.cnblogs.com/trouble-easy/p/12966903.html
Copyright © 2011-2022 走看看