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

    二叉树中和为某一值的路径

    题目描述

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

    注意, 是从跟节点一直到叶子节点的所有路径的val加起来, 不是某一段路径(最开始理解错误),

    class Solution {
    public:
        vector<vector<int> > buffer;
        vector<int> temp;
    
        void sort(vector<vector<int> > &vt) {
            for (int i = vt.size() - 1; i > 1; i--) {
                for (int j = i; j > 1; j--) {
                    if (vt[j] < vt[j-1]) {
                        vector<int> tmp = vt[j];
                        vt[j] = vt[i];
                        vt[i] = tmp;
                    }
                }
            }
        }
        
        vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
            if (NULL == root) {
                return buffer;
            }
            temp.push_back(root->val);
            if ((root->val == expectNumber) && (NULL == root->left) && (NULL == root->right)) {
                buffer.push_back(temp);
            }
            
            FindPath(root->left, expectNumber - root->val);
            FindPath(root->right, expectNumber - root->val);
            
    		if (!temp.empty()) {	// ---->遍历一条完整的路径后, 要把这个路径上的节点弹出来, 好遍历下条路径
                temp.pop_back();
            }
    
            sort(buffer);
            return buffer;
        }
    };
    
    /*
    struct TreeNode {
    	int val;
    	struct TreeNode *left;
    	struct TreeNode *right;
    	TreeNode(int x) :
    			val(x), left(NULL), right(NULL) {
    	}
    };*/
    
  • 相关阅读:
    内联函数(inline function)
    被extern "C" 修饰后按照C语言编译
    函数重载-name mangling或mame decoration技术-看看反汇编
    cin、cout
    下载visual studio 环境搭建
    配置共享文件夹
    EFS加密文件系统
    十二、字符串(1)
    十五、文件
    十一、指针
  • 原文地址:https://www.cnblogs.com/hesper/p/10477244.html
Copyright © 2011-2022 走看看