144. Binary Tree Preorder Traversal
題目:
https://leetcode.com/problems/binary-tree-preorder-traversal/
難度:
Medium
Recursive
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
res = []
self.preorder(root,res)
return res
def preorder(self,root,res):
if root == None:
return
res.append(root.val)
self.preorder(root.left,res)
self.preorder(root.right,res)
Iterative
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
res = []
stack = []
stack.append(root)
while stack:
node = stack.pop()
res.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res