描述
給出一棵二叉樹何暮,返回其節(jié)點(diǎn)值的前奄喂、中、后序遍歷跨新。
樣例
給出一棵二叉樹 {1,#,2,3},
1
2
/
3
返回 [3,2,1]
挑戰(zhàn)
你能使用非遞歸實(shí)現(xiàn)么?
代碼(遞歸)
前序遍歷
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Preorder in ArrayList which contains node values.
"""
def preorderTraversal(self, root):
# write your code here
result = []
if root is None:
return result
queue = [root]
while queue:
root = queue.pop()
result.append(root.val)
if root.right is not None:
queue.append(root.right)
if root.left is not None:
queue.append(root.left)
return result
中序遍歷
第一種寫法
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Inorder in ArrayList which contains node values.
"""
def inorderTraversal(self, root):
# write your code here
if root is None:
return []
stack = [root]
result = []
while stack:
new_root = stack.pop()
if new_root.left is not None:
stack.append(new_root)
stack.append(new_root.left)
continue
else:
result.append(new_root.val)
while new_root.right is None:
try:
new_root = stack.pop()
except IndexError:
return result
result.append(new_root.val)
stack.append(new_root.right)
return result
第二種寫法
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Inorder in ArrayList which contains node values.
"""
def inorderTraversal(self, root):
# write your code here
if root is None:
return []
stack = [root]
result = []
while stack:
new_root = stack[-1]
if new_root.left is None and new_root.right is None:
result.append(new_root.val)
stack.pop()
while stack:
new_root = stack.pop()
result.append(new_root.val)
if new_root.right is not None:
stack.append(new_root.right)
break
else:
if new_root.left is not None:
stack.append(new_root.left)
else:
if new_root.right is not None:
stack.pop()
result.append(new_root.val)
stack.append(new_root.right)
return result
后序遍歷
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: A Tree
@return: Postorder in ArrayList which contains node values.
"""
def postorderTraversal(self, root):
# write your code here
result = []
if root is None:
return result
stack = [root]
already = []
while stack:
new_root = stack.pop()
if new_root in already:
result.append(new_root.val)
continue
if new_root.left is None and new_root.right is None:
result.append(new_root.val)
else:
stack.append(new_root)
already.append(new_root)
if new_root.right is not None:
stack.append(new_root.right)
if new_root.left is not None:
stack.append(new_root.left)
return result