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. // Initializer list avoids the val = val shadowing bug
  10. TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  11. };
  12.  
  13. // Builds a binary tree from level-order array input (-1 denotes NULL)
  14. TreeNode* buildTree(const vector<int>& nodes) {
  15. if (nodes.empty() || nodes[0] == -1) return nullptr;
  16.  
  17. TreeNode* root = new TreeNode(nodes[0]);
  18. queue<TreeNode*> q;
  19. q.push(root);
  20.  
  21. int i = 1;
  22. while (!q.empty() && i < nodes.size()) {
  23. TreeNode* curr = q.front();
  24. q.pop();
  25.  
  26. // Left child
  27. if (i < nodes.size() && nodes[i] != -1) {
  28. curr->left = new TreeNode(nodes[i]);
  29. q.push(curr->left);
  30. }
  31. i++;
  32.  
  33. // Right child
  34. if (i < nodes.size() && nodes[i] != -1) {
  35. curr->right = new TreeNode(nodes[i]);
  36. q.push(curr->right);
  37. }
  38. i++;
  39. }
  40. return root;
  41. }
  42.  
  43. // Inorder traversal to print values
  44. void printInorder(TreeNode* root) {
  45. if (!root) return;
  46. printInorder(root->left);
  47. cout << root->val << " ";
  48. printInorder(root->right);
  49. }
  50.  
  51. // Level-order traversal (BFS) to print level by level
  52. void printLevelOrder(TreeNode* root) {
  53. if (!root) {
  54. cout << "Empty tree\n";
  55. return;
  56. }
  57. queue<TreeNode*> q;
  58. q.push(root);
  59. while (!q.empty()) {
  60. TreeNode* curr = q.front();
  61. q.pop();
  62. cout << curr->val << " ";
  63. if (curr->left) q.push(curr->left);
  64. if (curr->right) q.push(curr->right);
  65. }
  66. cout << "\n";
  67. }
  68.  
  69. int main() {
  70. // -------------------------------------------------------------
  71. // Option 1: Direct Vector Input (LeetCode style: [1, 2, 3, -1, 4])
  72. // -------------------------------------------------------------
  73. vector<int> sample = {1, 2, 3, -1, 4, 5, 6};
  74. TreeNode* root1 = buildTree(sample);
  75.  
  76. cout << "Tree 1 Inorder: ";
  77. printInorder(root1);
  78. cout << "\nTree 1 Level Order: ";
  79. printLevelOrder(root1);
  80.  
  81. // -------------------------------------------------------------
  82. // Option 2: Dynamic input from cin
  83. // Input format: N followed by N integers (use -1 for NULL)
  84. // -------------------------------------------------------------
  85. /*
  86.   int n;
  87.   if (cin >> n) {
  88.   vector<int> arr(n);
  89.   for (int i = 0; i < n; i++) cin >> arr[i];
  90.   TreeNode* root2 = buildTree(arr);
  91.  
  92.   cout << "Custom Tree Inorder: ";
  93.   printInorder(root2);
  94.   cout << "\n";
  95.   }
  96.   */
  97.  
  98. return 0;
  99. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Tree 1 Inorder: 2 4 1 5 3 6 
Tree 1 Level Order: 1 2 3 4 5 6