Path SumII|leetcode题解

来源:互联网 发布:微信聊天数据迁移 编辑:程序博客网 时间:2024/06/08 20:05

这题使用树的先序遍历,同时存储路径就可以解决。

    void preOrder(vector<vector<int> >&paths,TreeNode *root, int sum, vector<int>&path,int level){       if(NULL==root->left&&NULL==root->right){            if(sum==root->val){                path.push_back(root->val);                paths.push_back(path);            }            return;        }        //if(sum<=root->val)return;        sum-=root->val;        path.push_back(root->val);        if(root->left)preOrder(paths,root->left,sum,path,level+1);             path.resize(level);//访问由子树前,恢复path状态        if(root->right)preOrder(paths,root->right,sum,path,level+1);      }    vector<vector<int> > pathSum(TreeNode *root, int sum) {        vector<vector<int> >paths;        if(NULL==root) return paths;        vector<int>path;         preOrder(paths,root,sum,path,1);        return paths;    }
写递归函数时,要注意递归函数的出口和调用递归函数时的状态。

0 0
原创粉丝点击