fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct TreeNode {
  5. int val;
  6. TreeNode *left;
  7. TreeNode *right;
  8.  
  9. TreeNode() : val(0), left(nullptr), right(nullptr) {}
  10. TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  11. TreeNode(int x, TreeNode *left, TreeNode *right)
  12. : val(x), left(left), right(right) {}
  13. };
  14.  
  15. class Solution {
  16. public:
  17. vector<int> inorderTraversal(TreeNode* root) {
  18. vector<int> result;
  19. inOrder(root, result);
  20. return result;
  21. }
  22.  
  23. private:
  24. void inOrder(TreeNode* node, vector<int>& result) {
  25. if (!node) return;
  26. inOrder(node->left, result);
  27. result.push_back(node->val);
  28. inOrder(node->right, result);
  29. }
  30. };
  31.  
  32. int main() {
  33.  
  34.  
  35. TreeNode* root = new TreeNode(1);
  36. root->left = new TreeNode(2);
  37. root->right = new TreeNode(3);
  38. root->left->left = new TreeNode(4);
  39. root->left->right = new TreeNode(5);
  40.  
  41. Solution sol;
  42. vector<int> result = sol.inorderTraversal(root);
  43.  
  44. cout << "Inorder traversal: ";
  45. for (int val : result) {
  46. cout << val << " ";
  47. }
  48. cout << endl;
  49.  
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Inorder traversal: 4 2 5 1 3