描述
给出一棵二叉树,返回其节点值的前、中、后序遍历。
样例
给出一棵二叉树 {1,#,2,3},
1
2
/
3
返回 [3,2,1]
挑战
你能使用非递归实现么?
代码(递归)
前序遍历
"""
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