Introduction
Binary tree traversal is a fundamental operation for analyzing and manipulating binary trees. In this blog, we will focus on the in-order traversal of a binary tree.
Problem Statement
Given a binary tree, perform an in-order traversal of its nodes and return the values in a vector.
/**
* 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) {}
* };
*/
Algorithmic Approach
We will perform the in-order traversal of the binary tree recursively using the helper function inorderTraversalRecurser
. The function takes in a TreeNode
and a reference to a vector<int>
to store the values in the order of traversal. The helper function recursively traverses the left subtree, then adds the node value to the vector and finally recursively traverses the right subtree. The values are added to the vector in the order of traversal.
vector<int> inorderTraversalRecursive(TreeNode *root)
{
vector<int> res;
inorderTraversalRecurser(root, res);
return res;
}
void inorderTraversalRecurser(TreeNode *node, vector<int> &res)
{
if (node == NULL)
{
return;
}
inorderTraversalHelper(node->left, res);
res.push_back(node->val);
inorderTraversalHelper(node->right, res);
}
Time Complexity
For the Binary Tree Inorder Traversal algorithm, the time complexity is O(n), where n is the number of nodes in the binary tree. This is because we need to visit each node once to perform the inorder traversal. In the worst case, if the binary tree is skewed, the time complexity can be O(n^2), as we need to visit each node multiple times.
Space Complexity
The space complexity of the recursive implementation of the algorithm is O(n), where n is the number of nodes in the binary tree. This is because each recursive call adds a new stack frame to the call stack, which takes up space. In the worst case, if the binary tree is skewed, the space complexity can be O(n), as there can be n recursive calls on the call stack at the same time.
The space complexity of the iterative implementation of the algorithm is O(h), where h is the height of the binary tree. This is because we only need to store nodes on the current path from the root to the leftmost leaf node on the call stack. In the worst case, if the binary tree is skewed, the space complexity can be O(n), as the height of the binary tree can be n.
Conclusion
In this blog, we have discussed the in-order traversal of a binary tree and provided an algorithmic approach to implement it. We have also analyzed the time and space complexity of the algorithm. The provided code uses recursion to perform the traversal, but there are also other approaches, such as iterative methods using stacks or Morris traversal.