144. Binary Tree Preorder Traversal 先序遍历二叉树
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
# Definition for a binary tree node.# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution:def preorderTraversal(self, root):""":type root: TreeNode:rtype: List[int]"""res = []stack = [root]while stack and stack[0]:node = stack.pop()res.append(node.val)if node.right:stack.append(node.right)if node.left:stack.append(node.left)return res

浙公网安备 33010602011771号