• [笔试面试][code_by_hand]从二元树中找出和为某一值的所有路径


     1 View Code 
     2  #include <iostream>
     3  #include <vector>
     4  using namespace std;
     5  
     6  
     7  struct BinaryTreeNode
     8  {
     9          int m_nValue;
    10          BinaryTreeNode * m_pLeft;
    11          BinaryTreeNode * m_pRight;
    12  };
    13  
    14  
    15  void print(vector<int> & v)
    16  {
    17          for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
    18          {
    19                  cout<<*it<<" ";
    20          }
    21          cout<<endl;
    22  }
    23  
    24  
    25  void travel(BinaryTreeNode * root, vector<int> &v, int total, int &current)
    26  {
    27     if(root==NULL)
    28     {
    29         return;
    30     }
    31          v.push_back(root->m_nValue);
    32          current += root->m_nValue;
    33  
    34  
    35          if (current == total)
    36          {
    37                  print(v);
    38          }
    39  
    40  
    41          if (root->m_pLeft != NULL)
    42          {
    43                  travel(root->m_pLeft, v, total, current);
    44          }
    45          if (root->m_pRight != NULL)
    46          {
    47                  travel(root->m_pRight, v, total, current);
    48          }
    49  
    50  
    51          v.pop_back();
    52          current -= root->m_nValue;
    53  }
    54  
    55  
    56  BinaryTreeNode * buildnode(int num = 0, BinaryTreeNode * left = NULL, BinaryTreeNode * right = NULL)
    57  {
    58          BinaryTreeNode * res = new BinaryTreeNode();
    59          res->m_nValue = num;
    60          res->m_pLeft = left;
    61          res->m_pRight = right;
    62          return res;
    63  }
    64  
    65  
    66  int main()
    67  {
    68          BinaryTreeNode * root = buildnode(10, buildnode(5, buildnode(4), buildnode(7, buildnode(3, NULL, buildnode(-3)))), buildnode(12));
    69          vector<int> v;
    70          int total = 22;
    71          int current = 0;
    72          travel(root, v, total, current);
    73          return 0;
    74  }
  • 相关阅读:
    ACM spiral grid
    ACM 数独
    Codeforces Round #242 (Div. 2) A. Squats
    Codeforces Round #242 (Div. 2) B. Megacity
    Codeforces Round #242 (Div. 2) C. Magic Formulas
    Coder-Strike 2014
    Coder-Strike 2014
    Coder-Strike 2014
    ACM Same binary weight
    C puzzles详解【13-15题】
  • 原文地址:https://www.cnblogs.com/wendelhuang/p/3067146.html
Copyright © 2020-2023  润新知