
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 <stdio.h>
2#include <stdlib.h>
3
4struct TreeNode {
5 int val;
6 struct TreeNode *left;
7 struct TreeNode *right;
8};
9
10void inorderTraversalHelper(struct TreeNode* root, int* returnSize, int* result) {
11 if (!root) return;
12 inorderTraversalHelper(root->left, returnSize, result);
13 result[(*returnSize)++] = root->val;
14 inorderTraversalHelper(root->right, returnSize, result);
15}
16
17int* inorderTraversal(struct TreeNode* root, int* returnSize) {
18 *returnSize = 0;
19 int* result = (int*)malloc(100 * sizeof(int));
20 inorderTraversalHelper(root, returnSize, result);
21 return result;
22}The C solution defines a helper function inorderTraversalHelper to perform the recursion. The function is called with the current node and a result array to store the values. This implementation assumes a maximum of 100 nodes and allocates space accordingly, which is suitable for the problem constraints but would require dynamic reallocation in a more general scenario.
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)
1using System.Collections.Generic;
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
public IList<int> InorderTraversal(TreeNode root) {
List<int> result = new List<int>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode current = root;
while (current != null || stack.Count > 0) {
while (current != null) {
stack.Push(current);
current = current.left;
}
current = stack.Pop();
result.Add(current.val);
current = current.right;
}
return result;
}
}In C#, the iterative approach uses the .NET Stack class to iterate over the tree nodes in an inorder fashion. This stack management is critical for maintaining state between node processing.