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

    原文地址:https://www.jianshu.com/p/480b03915b99

    时间限制:1秒 空间限制:32768K

    题目描述

    输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

    我的代码

    /*
    struct TreeNode {
    	int val;
    	struct TreeNode *left;
    	struct TreeNode *right;
    	TreeNode(int x) :
    			val(x), left(NULL), right(NULL) {
    	}
    };*/
    class Solution {
    public:
        vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
            vector<vector<int>> res;
            vector<int> trace;
            if(root==nullptr)
                return res;
            FindPathCore(res,trace,root,expectNumber);
            return res;
        }
        void FindPathCore(vector<vector<int>> &res, vector<int> &trace, 
                      TreeNode* root,int expectNumber){
            trace.push_back(root->val);
            if(root->val==expectNumber && root->left==nullptr && root->right==nullptr)
                res.push_back(trace);
            if(root->left)
                FindPathCore(res,trace,root->left,expectNumber-root->val);
            if(root->right)
                FindPathCore(res,trace,root->right,expectNumber-root->val);
            trace.pop_back();
            return;
        }
    };
    

    运行时间:5ms
    占用内存:600k

  • 相关阅读:
    精准医疗
    生物信息学的研究过程
    蛋白质结构预测
    CP
    基因组大小控制因素
    RNA组研究困难
    输入input文本框的 U+202D和U+202C是什么
    ruby-get-url-query-params
    golang send post request
    nginx location配置
  • 原文地址:https://www.cnblogs.com/cherrychenlee/p/10796694.html
Copyright © 2011-2022 走看看