144. Binary Tree Preorder Traversal (easy)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans, stack = [] , []
stack.append(root)
while stack:
curNode = stack.pop()
if curNode:
ans.append(curNode.val)
stack.append(curNode.right)
stack.append(curNode.left)
return ans
94. Binary Tree Inorder Traversal (easy)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def dfs(node):
if not node:
return
dfs(node.left)
ans.append(node.val)
dfs(node.right)
dfs(root)
return ans
145. Binary Tree Postorder Traversal (easy)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def dfs(node):
if not node:
return
dfs(node.left)
dfs(node.right)
ans.append(node.val)
dfs(root)
return ans