Inorder Traversal of a Binary Tree using Iteration
Visualization Player
Problem Statement
Examples
Solution
Algorithm Steps
Code
C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}
int* inorderTraversal(TreeNode* root, int* returnSize) {
int* result = malloc(100 * sizeof(int));
TreeNode** stack = malloc(100 * sizeof(TreeNode*));
int top = -1, index = 0;
TreeNode* current = root;
while (current || top >= 0) {
while (current) {
stack[++top] = current;
current = current->left;
}
current = stack[top--];
result[index++] = current->val;
current = current->right;
}
*returnSize = index;
free(stack);
return result;
}
int main() {
TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
int returnSize;
int* res = inorderTraversal(root, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d ", res[i]);
}
printf("\n");
free(res);
return 0;
}
Comments
Loading comments...