pre
import typing
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
stack = [root]
ans = []
while stack:
cur = stack.pop()
ans.append(cur.val)
if cur.right:
stack.append(cur.right)
if cur.left:
stack.append(cur.left)
return ans
post
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
stack1, stack2 = [root], []
if not root:
return []
while stack1:
cur = stack1.pop()
if cur.left:
stack1.append(cur.left)
if cur.right:
stack1.append(cur.right)
stack2.append(cur.val)
return stack2[::-1]
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
stack = []
ans = []
while root:
stack.append(root)
root = root.left
while stack:
cur = stack.pop()
ans.append(cur.val)
if cur.right:
cur = cur.right
while cur:
stack.append(cur)
cur = cur.left
return ans