




Sponsored
Sponsored
This approach uses recursion to traverse the binary tree. Inorder traversal involves visiting the left subtree, the root node, and then the right subtree. The base case for the recursion is to return if the current node is null.
Time Complexity: O(n), where n is the number of nodes in the binary tree.
Space Complexity: O(n) due to the recursion stack.
1#include <vector>
2using namespace std;
3
4struct TreeNode {
5    int val;
6    TreeNode *left;
7    TreeNode *right;
8    TreeNode() : val(0), left(nullptr), right(nullptr) {}
9    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
10    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
11};
12
13void inorder(TreeNode* root, vector<int>& result) {
14    if (!root) return;
15    inorder(root->left, result);
16    result.push_back(root->val);
17    inorder(root->right, result);
18}
19
20vector<int> inorderTraversal(TreeNode* root) {
21    vector<int> result;
22    inorder(root, result);
23    return result;
24}In C++, recursion is used in a helper function inorder, which takes the current node and a reference to a result vector. If the node is not null, it processes the left subtree, adds the current node's value to the result, and then processes the right subtree.
In this approach, we use a stack to perform an iterative inorder traversal. The stack is utilized to track the nodes to be visited. This method mimics the recursive behavior by explicitly using a stack to push left children until reaching a null entry, then processes the nodes and explores the right subtrees.
Time Complexity: O(n)
Space Complexity: O(n)
1
The C implementation employs a manual stack data structure to facilitate the iterative traversal. Nodes are pushed onto the stack until null is reached, allowing us to backtrack, visit the node, and repeat the process for the right subtree.