# # 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
# # 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
classSolution: defpreorderTraversal(self, root: Optional[TreeNode]) -> List[int]: ans = [] st = [root] while st: thisNode = st.pop() ifnot thisNode: continue ans.append(thisNode.val) st.append(thisNode.right) st.append(thisNode.left) return ans