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 inorderTraversal(self, root):
pstack=[]
rst=[]
p=root
while p or pstack:
while p:
pstack.append(p)
p=p.left
p=pstack.pop()
rst.append(p.val)
p=p.right
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 recur(self, root, rst):
if not root: return
self.recur(root.left, rst)
rst.append(root.val)
self.recur(root.right,rst)
return
def inorderTraversal(self, root):
rst=[]
self.recur(root, rst)
return rst
No comments :
Post a Comment