剑指offer之二叉树中和为某一值的路径
二叉树中和为某一值的路径
https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca?tpId=13&&tqId=11177&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目
请在这里输入输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路
思路很简单,但是说起来很费劲,贴个链接吧:https://blog.csdn.net/niqian6005/article/details/97960184
代码
class Solution {
public:
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if (!root)
{
return path1;
}
path2.push_back(root->val);
expectNumber -= root->val;
if ((!root->left) && (!root->right)&& (expectNumber == 0))
{
path1.push_back(path2);
}
FindPath(root->left, expectNumber);
FindPath(root->right, expectNumber);
path2.pop_back();
return path1;
}
private:
vector<vector<int> > path1;
vector<int> path2;
};
美的集团公司福利 715人发布
查看7道真题和解析