fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct BinaryTreeNode {
  5. BinaryTreeNode* left;
  6. BinaryTreeNode* right;
  7. int val;
  8.  
  9. BinaryTreeNode(int value) {
  10. left = NULL;
  11. right = NULL;
  12. val = value;
  13. }
  14. };
  15.  
  16. void inorder(BinaryTreeNode* root) {
  17. if (root == NULL)
  18. return;
  19.  
  20. inorder(root->left);
  21. cout << root->val << " ";
  22. inorder(root->right);
  23. }
  24.  
  25. void preorder(BinaryTreeNode* root) {
  26. if (root == NULL)
  27. return;
  28.  
  29. cout << root->val << " ";
  30. preorder(root->left);
  31. preorder(root->right);
  32. }
  33.  
  34. void postorder(BinaryTreeNode* root) {
  35. if (root == NULL)
  36. return;
  37.  
  38. postorder(root->left);
  39. postorder(root->right);
  40. cout << root->val << " ";
  41. }
  42.  
  43. int SumOfAllNodes(BinaryTreeNode* root) {
  44. if (root == NULL)
  45. return 0;
  46. return root->val + SumOfAllNodes(root->left) + SumOfAllNodes(root->right);
  47. }
  48.  
  49. int calculateHeightOfTree(BinaryTreeNode* root) {
  50. if (root == NULL)
  51. return 0;
  52. int leftHeight = calculateHeightOfTree(root->left);
  53. int rightHeight = calculateHeightOfTree(root->right);
  54. return 1 + max(leftHeight, rightHeight);
  55. }
  56.  
  57. int main() {
  58. BinaryTreeNode* root = new BinaryTreeNode(5);
  59. BinaryTreeNode* leftNode = new BinaryTreeNode(2);
  60. BinaryTreeNode* rightNode = new BinaryTreeNode(7);
  61. BinaryTreeNode* leftLeft = new BinaryTreeNode(1);
  62. BinaryTreeNode* leftRight = new BinaryTreeNode(3);
  63.  
  64. root->left = leftNode;
  65. root->right = rightNode;
  66. leftNode->left = leftLeft;
  67. leftNode->right = leftRight;
  68.  
  69. cout << "Inorder Traversal: ";
  70. inorder(root);
  71. cout << endl;
  72.  
  73. cout << "Preorder Traversal: ";
  74. preorder(root);
  75. cout << endl;
  76.  
  77. cout << "Postorder Traversal: ";
  78. postorder(root);
  79. cout << endl;
  80.  
  81. cout << "Sum of all nodes: " << SumOfAllNodes(root) << endl;
  82. cout << "Height of tree: " << calculateHeightOfTree(root) << endl;
  83.  
  84. return 0;
  85. }
  86.  
Success #stdin #stdout 0.01s 5300KB
stdin
Standard input is empty
stdout
Inorder Traversal: 1 2 3 5 7 
Preorder Traversal: 5 2 1 3 7 
Postorder Traversal: 1 3 2 7 5 
Sum of all nodes: 18
Height of tree: 3