• [LeetCode] 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]
    ]

    思路: 参考资料https://leetcode.com/discuss/45131/12ms-11-lines-c-solution
        时间复杂度O(n),空间复杂度O(lgN)

    相关题目:《剑指offer》面试题25

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<vector<int> > pathSum(TreeNode *root, int sum) {
    13         vector<vector<int> > result;
    14         if (root == NULL) 
    15             return result;
    16             
    17         vector<int> path;
    18         pathSum(root, sum, result, path);
    19         
    20         return result;
    21     }
    22     
    23     void pathSum(TreeNode *root, int sum, vector<vector<int> > &result, vector<int> &path) {
    24         path.push_back(root->val);
    25         
    26         if (root->left == NULL && root->right == NULL) {
    27             if (root->val == sum) {
    28                 result.push_back(path);
    29             } 
    30         } 
    31         
    32         if (root->left) 
    33             pathSum(root->left, sum - root->val, result, path);
    34             
    35         if (root->right)
    36             pathSum(root->right, sum - root->val, result, path);
    37         
    38         path.pop_back();
    39             
    40     }
    41 };
  • 相关阅读:
    Mysql里的isnull(),ifnull(),nullif
    懒加载数据
    MyEclipse编辑xml文件没有提示
    java-五子棋游戏源码
    Java版打字练习游戏源码
    Wpf实现图片自动轮播自定义控件
    WP8.1开发:自定义控件
    简单的UIButton按钮动画效果ios源码下载
    自定义的一款选项卡ios源码
    Aisen微博应用源码完整版
  • 原文地址:https://www.cnblogs.com/vincently/p/4130504.html
Copyright © 2020-2023  润新知