# 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]: if root isNone : return [] stack = [] result = []
stack.append(root) while stack : node = stack.pop() result.append(node.val)
if node.right : stack.append(node.right) if node.left : stack.append(node.left)