Skip to main content

Binary Tree Inorder Traversal

Problem

Given the root of a binary tree, return the inorder traversal of its nodes' values.

Solution Approach

Expected Time complexity: O(n)O(n)

Click - to see solution code
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> inorder;
TreeNode* cur = root;
while (cur != NULL) {
if (cur->left == NULL) {
inorder.push_back(cur->val);
cur = cur->right;
} else {
TreeNode* prev = cur->left;
while (prev->right && prev->right != cur) {
prev = prev->right;
}

if (prev->right == cur) {
prev->right = NULL;
inorder.push_back(cur->val);
cur = cur->right;
} else {
prev->right = cur;
cur = cur->left;
}
}
}
return inorder;
}
};