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     }
  • 相关阅读:
    cart树剪枝
    LSA、LDA
    paddle中新增layer
    https://www.i5seo.com/
    打印机彩色打印设置(将彩色打印为黑色)
    办公文档的标准格式
    电脑常用的5个按键
    Win7各个版本之间的区别
    win7保护眼睛的颜色设置方法(85,125,205)
    详细教您台式电脑如何组装
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3414922.html
Copyright © 2011-2022 走看看