Advertisement
finalmail

dfs cpp

Aug 1st, 2020
1,618
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.90 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <math.h>
  5. #include <vector>
  6. #include <string>
  7.  
  8. using namespace std;
  9.  
  10. struct node {
  11.     int value;
  12.     vector<node*> children;
  13.     node(int v) {
  14.         value = v;;
  15.     }
  16. };
  17.  
  18. int dfs(node* n) {
  19.     if (!n) {
  20.         return 0;
  21.     }
  22.    
  23.     cout << n->value << endl;
  24.    
  25.     int m = 0;
  26.     for (node* it : n->children) {
  27.         m = max(m, dfs(it));
  28.     }
  29.    
  30.     return n->value + m;
  31. }
  32.  
  33. int main()
  34. {
  35.     node* n4 = new node(4);
  36.     node* n12 = new node(12);
  37.     node* n42 = new node(42);
  38.     node* n9 = new node(9);
  39.     node* n1 = new node(1);
  40.     node* root = new node(5);
  41.    
  42.     n1->children.push_back(n4);
  43.     n1->children.push_back(n12);
  44.     n1->children.push_back(n42);
  45.    
  46.     root->children.push_back(n9);
  47.     root->children.push_back(n1);
  48.    
  49.     int r = dfs(root);
  50.     cout << r << endl;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement