zoukankan      html  css  js  c++  java
  • Path Sum II

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

    For example:
    Given the below binary tree and sum = 22,

                  5
                 / 
                4   8
               /   / 
              11  13  4
             /      / 
            7    2  5   1
    

    return

    [
       [5,4,11,2],
       [5,8,4,5]
    ]
    

    Subscribe to see which companies asked this question

    /**
     * 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:
        void _get_path(TreeNode* root, int sum, int path_sum, vector<int> path_list, vector<vector<int>> &res_list) {
            if (NULL == root) {
                return;
            }
            path_sum = path_sum + root->val;
            path_list.push_back(root->val);
            cout << path_sum << endl;
            if (root->left == NULL  && root->right == NULL && sum == path_sum) {
                res_list.push_back(path_list);
            }
            if (root->left) {
                _get_path(root->left, sum, path_sum, path_list, res_list);
            }
            if (root->right) {
                _get_path(root->right, sum, path_sum, path_list, res_list);
            }
        }
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            vector<int> path_list;
            vector<vector<int>> res_list;
            int path_sum = 0;
            _get_path(root, sum, path_sum, path_list, res_list);
            return res_list;
        }
    };
  • 相关阅读:
    基于注解的IOC配置
    字符串典型问题分析
    指针与数组
    数组的本质
    数组与指针分析
    指针的本质
    #与##操作符使用
    #pragma使用分析
    #error和#line使用分析
    条件编译使用
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5215220.html
Copyright © 2011-2022 走看看