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

it2022-05-05  63

题目描述

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

思路:参考《剑指offer》

 

/* 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>> allPath; vector<int> path; int currentSum = 0; if(root == nullptr) return allPath; FindPath(root, expectNumber, path, currentSum, allPath); return allPath; } void FindPath(TreeNode* root, int expectNumber, vector<int> &path, int currentSum, vector<vector<int>> &allPath){ currentSum += root->val; path.push_back(root->val); //判断是否是叶节点 bool isLeaf = root->left == nullptr && root->right == nullptr; if(isLeaf && currentSum == expectNumber){ allPath.push_back(path); } if(root->left != nullptr) FindPath(root->left, expectNumber, path, currentSum, allPath); if(root->right != nullptr) FindPath(root->right, expectNumber, path, currentSum, allPath); path.pop_back(); } };

 


最新回复(0)