题解 | #二叉树中和为某一值的路径#

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

http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

class Solution {
public:
    void init_dfs(int cont,vector<vector<int> > &path,int &path_num,TreeNode* p,int expectNumber) {
        if (p==NULL)
        {
            return;
        }
        if (p->left == NULL && p->right == NULL)
        {
            if (p->val == expectNumber)
            {
                path.resize(path_num + 1);
                path[path_num].resize(cont + 1);
                path[path_num][cont] = p->val;
                path_num++;
            }
            return;
        }
        int minpath = path_num;

        if (p->left)
            init_dfs(cont + 1, path, path_num, p->left, expectNumber - p->val);
        if (p->right)
            init_dfs(cont + 1, path, path_num, p->right, expectNumber - p->val);
        for (int i = minpath; i < path_num; i++)    
            path[i][cont] = p->val;
        return;
    }
    vector<vector<int> > FindPath(TreeNode* root, int expectNumber) {
        vector<vector<int> > Path;
        int path_num = 0;
        TreeNode* p = root;
        init_dfs(0, Path, path_num, p, expectNumber);
        return Path;
    }
};
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务