欢迎找我内推微软

[剑指offer] 二叉树中和为某一值的路径

题目描述

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


 

依然是递归,一个关键点是把结果和当前路径与和存储为类的变量,减少了对结果集合和当前路径繁琐的合并与传递等操作。

 

/*
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> > re;
    vector<int> currentPath;
    int currentSum = 0;
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if (root == NULL) return re;
        currentPath.push_back(root->val);
        currentSum += root->val;
        if (currentSum == expectNumber && root->left == NULL && root->right == NULL) {
            re.push_back(currentPath);
        } else {
            FindPath(root->left, expectNumber);
            FindPath(root->right, expectNumber);
        }
        currentPath.pop_back();
        currentSum -= root->val;
        return re;
    }
};

 

posted @ 2017-11-28 13:05  zmj97  阅读(103)  评论(0编辑  收藏  举报
欢迎找我内推微软