题目描述
输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)
------------------------------------------------------------------------------------------------------------
/*
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> >res;
vector<int>bp;
int num = 0;
//stack<TreeNode*>node;
//自己还是没有完全理解前序遍历的实质含义,其实先序遍历和中序遍历就是利用栈实现的
//先遍历节点的左子树,当左子树为空时,从栈中pop一个元素,在遍历他的右子树,右子树再为空,在pop他的上一个节点,在访问
//右子树,而自己就错在想用一个栈来模拟实现这一个过程。
//其实二叉树的前序遍历和中序遍历是尾递归,就是用栈实现的
vector<vector<int> > FindPath(TreeNode* root,int expectNumber)
{
FindPath1(root, expectNumber);
return res;
}
void FindPath1(TreeNode* root, int expectNumber)
{
if (!root)return;
bp.push_back(root->val);
if (!root->left && !root->right&&expectNumber == root->val )
{
res.push_back(bp);
}
else
{
if (root->left)FindPath1(root->left, expectNumber-root->val);
if (root->right)FindPath1(root->right, expectNumber-root->val);
}
bp.pop_back();//这个应该是跟随栈一起pop
}
};