Advertisement
Guest User

CountNodes.cpp

a guest
Aug 8th, 2017
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.68 KB | None | 0 0
  1. /* C89 */
  2. #include <stddef.h> /* size_t */
  3.  
  4. struct Node {
  5.     struct Node *left;
  6.     struct Node *right;
  7.     void *data;
  8. };
  9.  
  10. static size_t count_nodes(struct Node root)
  11. {
  12.     size_t n = 1;
  13.  
  14.     if (root.left)
  15.         n += count_nodes(*root.left);
  16.     if (root.right)
  17.         n += count_nodes(*root.right);
  18.  
  19.     return n;
  20. }
  21.  
  22. // C++1z
  23. #include <cstddef> // size_t
  24. #include <optional> // optional
  25. using std::optional;
  26. using std::size_t;
  27.  
  28. template<class T>
  29. struct Node {
  30.     optional<Node> left;
  31.     optional<Node> right;
  32.     T value;
  33.  
  34.     constexpr size_t count_nodes() const
  35.     {
  36.         size_t n = 1;
  37.  
  38.         if (left)
  39.             n += left->count_nodes();
  40.         if (right)
  41.             n += right->count_nodes();
  42.  
  43.         return n;
  44.     }
  45. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement