144. Binary Tree Preorder Traversal

# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ s = [] # use as a stack res = [] # stores result if (root == None): return res else: s.append(root) while(s): # if s is empty, s is False. not s is True curr = s.pop() res.append(s.val) s.append(s.right) # pre-order print left first, so push right first s.append(s.left) return res
可以优化。见下一个帖子。

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.