zoukankan      html  css  js  c++  java
  • Leetcode 113

    /**
     * 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();
        }
    };

    ——这个和上一题对应

  • 相关阅读:
    Metronic最优秀的基于Bootstrap的响应式网站模版
    SMINT:单页网站的免費jQuery插件
    不做全栈开发工程师
    《劲道》课程笔记——教练对话
    windows 7环境下配置oracle 11g 客户端
    jsp+servlet+javabean (MVC)分页
    解析java中 hashcode()
    BeanUtils操作
    Dom4jApp.java 解析和创建XML
    dom4j
  • 原文地址:https://www.cnblogs.com/cunyusup/p/10348257.html
Copyright © 2011-2022 走看看