
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.
1using System.Collections.Generic;
2
3public class TreeNode {
4 public int val;
5 public TreeNode left;
6 public TreeNode right;
7 public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
8 this.val = val;
9 this.left = left;
10 this.right = right;
11 }
12}
13
14public class Solution {
15 public IList<int> InorderTraversal(TreeNode root) {
16 List<int> result = new List<int>();
17 Inorder(root, result);
18 return result;
19 }
20
21 private void Inorder(TreeNode node, List<int> result) {
22 if (node == null) return;
23 Inorder(node.left, result);
24 result.Add(node.val);
25 Inorder(node.right, result);
26 }
27}The C# implementation utilizes a helper method Inorder which recursively visits nodes in the inorder sequence and fills a list with the nodes' values.
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.