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

xiaoxiao2021-02-28  90

题目描述

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

/* 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> > re; vector<int> path; if(root==NULL) return re; recurTrav(root,expectNumber,re,path); return re; } void recurTrav(TreeNode* root,int expectNumber,vector<vector<int> >& re,vector<int> path){ if(root==NULL) return; expectNumber-=root->val; if(expectNumber>=0){ path.push_back(root->val); if(expectNumber==0&&root->left==NULL&&root->right==NULL) re.push_back(path); else{ recurTrav(root->left,expectNumber,re,path); recurTrav(root->right,expectNumber,re,path); } } else return; } };

转载请注明原文地址: https://www.6miu.com/read-49910.html

最新回复(0)