# 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: TreeNode) -> List[int]: res = [] def handle(root): if not root: return res.append(root.val) handle(root.left) handle(root.right) handle(root) return res
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func preorderTraversal(root *TreeNode) []int { res := []int{} var handle func(*TreeNode) handle = func(root *TreeNode) { if root== nil { return } res = append(res, root.Val) handle(root.Left) handle(root.Right) return } handle(root) return res }
# 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: TreeNode) -> List[int]: stack = [] node = root res = [] while node or stack: while node: res.append(node.val) stack.append(node) node = node.left node = stack[-1].right stack = stack[:len(stack)-1] return res