Iterative solution:
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def preorderTraversal(self, root):
prelist=[]
rst=[]
if root==None:
return rst
prelist.append(root)
while(prelist):
crt=prelist.pop()
rst.append(crt.val)
if crt.right:
prelist.append(crt.right)
if crt.left:
prelist.append(crt.left)
return rst
Recursive solution:
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def preorderecur(self, root, rst):
if not root: return
rst.append(root.val)
self.preorderecur(root.left,rst)
self.preorderecur(root.right,rst)
return
def preorderTraversal(self, root):
rst=[]
self.preorderecur(root,rst)
return rst
No comments :
Post a Comment