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]
    ]

    代码:
     1     vector<vector<int> > pathSum(TreeNode *root, int sum) {
     2         // IMPORTANT: Please reset any member data you declared, as
     3         // the same Solution instance will be reused for each test case.
     4         vector<vector<int> > result;
     5         result.clear();
     6         if(root == NULL)
     7             return result;
     8         if(root->val == sum && root->left == NULL && root->right == NULL){
     9             vector<int> tmp(1, sum);
    10             result.push_back(tmp);
    11             return result;
    12         }
    13         vector<vector<int> > lresult = pathSum(root->left, sum-root->val);
    14         vector<vector<int> > rresult = pathSum(root->right, sum-root->val);
    15         int n = lresult.size();
    16         for(int i = 0; i < n; i++){
    17             vector<int> tmp = lresult[i];
    18             tmp.insert(tmp.begin(), root->val);
    19             result.push_back(tmp);
    20         }
    21         n = rresult.size();
    22         for(int i = 0; i < n; i++){
    23             vector<int> tmp = rresult[i];
    24             tmp.insert(tmp.begin(), root->val);
    25             result.push_back(tmp);
    26         }
    27         return result;
    28     }
  • 相关阅读:
    网页制作
    线性表
    学习进度表
    我是一只IT小小鸟读后感
    Git分支管理(一)
    家庭因你而不同
    Mysql循环insert数据
    IDEA,右边栏不显示maven解决方案
    Linux定时清理日志脚本
    JAVA的夸平台特性的优势——工厂在线生产信息采集项目
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3414922.html
Copyright © 2011-2022 走看看