题目描述
输入一颗二叉树的根节点和一个整数,按字典序打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
解题思路
方法一:递归
1、思路:先序遍历,在遍历的过程中,先将当前结点值入栈,然后判断:
- 当前结点是叶子结点且其值等于所期望的值,则这条路径合法,保存此路径上的所有结点值;
- 当前结点不是叶子结点,递归判断其左子树和右子树,注意期望值要减去当前结点值;
回溯时表明已经不需要当前结点,结点值需要出栈。
2、代码:
/*
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> > result;
vector<int> singlePath;
void path(TreeNode* root, int expect) {
if (!root) return;
singlePath.push_back(root->val);
expect -= root->val;
if (!root->left && !root->right && expect == 0) {
result.push_back(singlePath);
}
path(root->left, expect);
path(root->right, expect);
singlePath.pop_back();
}
vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
if (!root) return result;
path(root, expectNumber);
return result;
}
};
3、复杂度:
时间复杂度:O(n),遍历一次树的所有结点;
空间复杂度:O(n),当树退化为链表,递归空间为O(n)。