Leetcode 94. Binary Tree Inorder Traversal
You are given the root of a binary tree. Implement an inorder traversal of the binary tree and return the values of the nodes in the traversal order.
Inorder traversal of a binary tree visits nodes in the following order:
We can implement this both recursively and iteratively. Here, we will focus on the iterative approach using a stack, which is a more common interview question variant.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include <vector>
#include <stack>
// Iterative approach using stack
class Solution {
public:
std::vector<int> inorderTraversal(TreeNode* root) {
std::vector<int> result;
std::stack<TreeNode*> s;
TreeNode* current = root;
while (current != nullptr || !s.empty()) {
// Reach the leftmost Node of the current Node
while (current != nullptr) {
s.push(current);
current = current->left;
}
// Current must be NULL at this point
current = s.top();
s.pop();
result.push_back(current->val); // Visit the node
// We have visited the node and its left subtree. Now it's the right subtree's turn
current = current->right;
}
return result;
}
};
The time complexity of this algorithm is (O(n)), where (n) is the number of nodes in the binary tree. Each node is visited exactly once.
The space complexity is also (O(n)) for the stack in the worst case, especially when the tree is completely unbalanced, i.e., each node has only one child (all left or all right nodes).
This structure ensures an efficient and clear solution to the problem using an iterative approach, which is often preferred in environments where recursion depth might be a concern.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?