forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0094-binary-tree-inorder-traversal.cs
48 lines (45 loc) · 1.33 KB
/
0094-binary-tree-inorder-traversal.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Definition for a binary tree node.
* 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) {
// return InorderTraversalRecursive(root).ToList();
return InorderTraversalIterative(root).ToList();
}
// Time: O(n)
// Space: O(n)
private IEnumerable<int> InorderTraversalRecursive(TreeNode node) {
if (node == null) {
return Enumerable.Empty<int>();
}
return InorderTraversalRecursive(node.left)
.Append(node.val)
.Concat(InorderTraversalRecursive(node.right));
}
// Time: O(n)
// Space: O(n)
private IEnumerable<int> InorderTraversalIterative(TreeNode node) {
List<int> result = new();
Stack<TreeNode> stack = new();
while (node != null || stack.Any()) {
while (node != null) {
stack.Push(node);
node = node.left;
}
node = stack.Pop();
result.Add(node.val);
node = node.right;
}
return result;
}
}