面试题25:二叉树中和为某一值的路径

来源:互联网 发布:抢魅族手机用什么软件 编辑:程序博客网 时间:2024/05/17 01:56

面试题25:二叉树中和为某一值的路径

题目描述:
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

题目分析:
路径指从根结点到叶子结点的一条路。题目实际过程是二叉树的遍历,二叉树遍历分为前序、中序、后序遍历,这里我选用前序遍历。

代码如下:

class Solution {public:    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {        vector<vector<int> > res;        if (root == 0)                                                                               return res;        vector<int> nums;        Find(root, expectNumber, nums, res);        return res;    }    void Find(TreeNode *root, int target, vector<int> &nums, vector<vector<int> > &res) {        nums.push_back(root->val);        if (IsLeaf(root) && root->val == target) {            res.push_back(nums);        }        if (root->left)            Find(root->left, target - root->val, nums, res);        if (root->right)            Find(root->right, target - root->val, nums, res);        nums.pop_back();    }    bool IsLeaf(TreeNode *node) {        if (node->left == 0 && node->right == 0)            return true;        else            return false;    }};
0 0