C++:输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
程序员文章站
2022-03-27 10:21:16
...
题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
提交代码:
class Solution {
public:
vector<vector<int>> v_final;
vector<int> temp_v;
vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {
if (root==NULL)
{
return v_final;
}
temp_v.push_back(root->val);
if (root->left==NULL&&root->right==NULL&&root->val ==expectNumber)
{
v_final.push_back(temp_v);
}
if (root->left!=NULL&&root->val<expectNumber)
{
FindPath(root->left, expectNumber - root->val);
}
if (root->right != NULL&&root->val < expectNumber)
{
FindPath(root->right, expectNumber - root->val);
}
temp_v.pop_back();
return v_final;
}
};
结果:
上一篇: CSAPP实验1:Data Lab笔记
下一篇: 区域生长算法原理以及Matlab实现