剑指offer24-二叉树中和为某一值的路径

题目描述

输入一颗二叉树的根节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)

思路:

1,若根节点不为null,则先将其装入路径集合中。

2,再进行判断,若其值与expectNumber相同,且左右子树为空,说明这条路径符合;

         若其值小于expectNumber,且左子树不为空,则以左子树和expectNumber-val(当前节点的值)为新的递归体,进行判断;

         若其值小于expectNumber,且右子树不为空,则以右子树和expectNumber-val(当前节点的值)为新的递归体,进行判断;

3,注意需要返回上一个节点。

        

/*
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> > allPath;
    //存放当前正在遍历的路径
    vector<int> tempPath;
    
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        if(root==NULL)
            return allPath;
        tempPath.push_back(root->val);
        
        if(root->val==expectNumber && root->left==NULL && root->right==NULL){
            allPath.push_back(tempPath);
        }
        if(root->val<expectNumber && root->left!=NULL)
            FindPath(root->left, expectNumber - root->val);
        if(root->val<expectNumber && root->right!=NULL)
            FindPath(root->right, expectNumber - root->val);
        //,返回上一个节点
        tempPath.pop_back();
        return allPath;
    }
};
//看了很多代码,思路几乎就上面一个

 

posted @ 2020-02-21 20:57  清心lh  阅读(156)  评论(0编辑  收藏  举报