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     }
  • 相关阅读:
    springmvc乱码问题
    51nod 还是01串
    51nod 1276 岛屿的数量
    poj 2486 a apple tree
    hdu 1011 Starship Troopers
    poj 1155 TELE
    hdu 4586 Play the Dice
    hdu 5023 A Corrupt Mayor's Performance Art(线段树水题)
    Appleman and Tree
    hdu 4003
  • 原文地址:https://www.cnblogs.com/waruzhi/p/3414922.html
Copyright © 2011-2022 走看看