二叉树中和为某一值的路径

来源:互联网 发布:法国航空发动机知乎 编辑:程序博客网 时间:2024/06/05 07:57

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

思路:首先进行分析题目,由于我们需要找到从根节点到叶节点的路径,因此必须首先访问根节点,之后才继续访问叶节点,在前中后序遍历中,只有前序遍历才会首先访问根节点,因此我们采用前序遍历。

在程序中,我们利用vector来存储路径,找到的路径放入到vector<vector<>>当中。

在allpath中,同时引入一个currentsum变量,用于记录当前遍历到的路径之和。

当currentsum==给定值,并且所遍历的节点是叶节点时,说明找到一条路径,直接加入到最终结果当中。

注意最后要将vector中的最后一个元素弹出。

/*

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> > FindPath(TreeNode* root,int expectNumber) {
        vector< vector<int> >res;
        vector<int> path;
        int currentsum=0;
        allpath(root,res,path,currentsum,expectNumber);
        return res;
    }
    void allpath(TreeNode* root, vector< vector<int> >& res, vector<int>& path, int currentsum,int expectNumber){
        if(root==NULL) return;
        currentsum+=root->val;
        path.push_back(root->val);
        bool isleaf=(root->left==NULL&&root->right==NULL)?true:false;
        if(currentsum==expectNumber&&isleaf){
            res.push_back(path);
        }
        if(root->left){
            allpath(root->left,res,path,currentsum,expectNumber);
        }
        if(root->right){
            allpath(root->right,res,path,currentsum,expectNumber);
        }
        path.pop_back();
    }
};
0 0
原创粉丝点击