码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 113

时间:2019-02-02 14:19:49      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:treenode   push   oid   add   dfs   out   leetcode   ret   ==   

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        if(root == NULL) return res;
        vector<int> add;
        add.push_back(root->val);
        DFS(res,add,root,sum,root->val);
        return res;
        
    }
    void DFS(vector<vector<int>>& res,vector<int>& add,TreeNode*root,int sum,int& he){
        if((root->left == NULL)&&(root->right == NULL)){
            if(he == sum) res.push_back(add);
        }
        else if((root->left != NULL)&&(root->right == NULL)){
            add.push_back(root->left->val);
            he += root->left->val;
            DFS(res,add,root->left,sum,he);
            add.pop_back();
            he -= root->left->val;
        }
        else if((root->left == NULL)&&(root->right != NULL)){
            add.push_back(root->right->val);
            he += root->right->val;
            DFS(res,add,root->right,sum,he);
            add.pop_back();
            he -= root->right->val;
        }
        else if((root->left != NULL)&&(root->right != NULL)){
            add.push_back(root->left->val);
            he += root->left->val;
            DFS(res,add,root->left,sum,he);
            add.pop_back();
            he -= root->left->val;
            add.push_back(root->right->val);
            he += root->right->val;
            DFS(res,add,root->right,sum,he);
            add.pop_back();
            he -= root->right->val;
        }
        return;
    }
};

_虽然代码丑,但比较好理解

class Solution {
public:
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        vector<vector<int>> res;
        vector<int> out;
        helper(root, sum, out, res);
        return res;
    }
    void helper(TreeNode* node, int sum, vector<int>& out, vector<vector<int>>& res) {
        if (!node) return;
        out.push_back(node->val);
        if (sum == node->val && !node->left && !node->right) {
            res.push_back(out);
        }
        helper(node->left, sum - node->val, out, res);
        helper(node->right, sum - node->val, out, res);
        out.pop_back();
    }
};

——这个和上一题对应

Leetcode 113

标签:treenode   push   oid   add   dfs   out   leetcode   ret   ==   

原文地址:https://www.cnblogs.com/cunyusup/p/10348257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!