while stack: node = stack.pop() if node: ret.append(node.val) stack.append(node.right) stack.append(node.left)
<precompiled.treenode.TreeNode object at 0x7f19ec21fc90> None None
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ ret = [] stack = [root] while stack: node = stack.pop() if node: ret.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return ret