1
+ """
2
+ Given the root of a binary tree, return the inorder traversal of its
3
+ nodes' values.
4
+
5
+ Example 1:
6
+ Input: root = [1,null,2,3]
7
+ Output: [1,3,2]
8
+
9
+ Example 2:
10
+ Input: root = []
11
+ Output: []
12
+
13
+ Example 3:
14
+ Input: root = [1]
15
+ Output: [1]
16
+
17
+ Constraints:
18
+ * The number of nodes in the tree is in the range [0, 100]
19
+ * -100 <= Node.val <= 100
20
+
21
+ Follow up: Recursive solution is trivial, could you do it iteratively?
22
+ """
23
+
24
+ class Solution :
25
+ # O(2^n) recursive solution, using default arg to collect result
26
+ #def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
27
+ # res = []
28
+ # self.helper(root, res)
29
+ # return res
30
+ #
31
+ #def helper(self, node, res=[]):
32
+ # if not node is None:
33
+ # self.helper(node.left, res)
34
+ # res.append(node.val)
35
+ # self.helper(node.right, res)
36
+
37
+ # O(2^n) recursive solution
38
+ #def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
39
+ # if root is None:
40
+ # return []
41
+ # res = self.inorderTraversal(root.left)
42
+ # res.append(root.val)
43
+ # res += self.inorderTraversal(root.right)
44
+ # return res
45
+
46
+ # O(2^n) iterative solution (breadth-first)
47
+ #def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
48
+ # if root is None:
49
+ # return []
50
+ #
51
+ # to_do = [root.right, root, root.left]
52
+ # visited = {root: True}
53
+ #
54
+ # res = []
55
+ # while len(to_do):
56
+ # curr = to_do[-1]
57
+ # if curr is None:
58
+ # to_do.pop()
59
+ # continue
60
+ #
61
+ # # Already visited or a leaf
62
+ # if curr in visited or (curr.left is None and curr.right is None):
63
+ # to_do.pop()
64
+ # res.append(curr.val)
65
+ # continue
66
+ #
67
+ # if not curr.right is None:
68
+ # to_do.insert(-1, curr.right)
69
+ # if not curr.left is None:
70
+ # to_do.append(curr.left)
71
+ #
72
+ # visited[curr] = True
73
+ #
74
+ # return res
75
+
76
+ # O(2^n) iterative solution (depth-first)
77
+ def inorderTraversal (self , root : Optional [TreeNode ]) -> List [int ]:
78
+ res = []
79
+ stack = []
80
+
81
+ while True :
82
+ while root :
83
+ stack .append (root )
84
+ root = root .left
85
+
86
+ if len (stack ) == 0 :
87
+ return res
88
+
89
+ curr = stack .pop ()
90
+ res .append (curr .val )
91
+ root = curr .right
0 commit comments