二叉树的实现:创建节点类
class treeNode:
def __init__(self, x):
self.left = None
self.right = None
self.val = x
solution包括了打印二叉树的函数,通过前序遍历和 中序遍历获得顺序输出的函数,求二叉树高度的代码。
class Solution:
#从上往下打印出二叉树的每个节点,同层节点从左至右打印
def PrintFromTopToBottom(self, root):
array = []
result = []
if root == None:
return result
array.append(root)
while array:
newNode = array.pop(0)
result.append(newNode.val)
if newNode.left != None:
array.append(newNode.left)
if newNode.right != None:
array.append(newNode.right)
return result
# 给定二叉树的前序遍历和中序遍历,获得该二叉树
def getBSTwithPreTin(self, pre, tin):
if len(pre)==0 | len(tin)==0:
return None
root = treeNode(pre[0])
for order,item in enumerate(tin):
if root .val == item:
root.left = self.getBSTwithPreTin(pre[1:order+1], tin[:order])
root.right = self.getBSTwithPreTin(pre[order+1:], tin[order+1:])
return root
#求二叉树的最大深度(即高度)
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: # 递归边界
return 0
else:
l = 1 + self.maxDepth(root.left) # 递归
r = 1 + self.maxDepth(root.right)
return max(l, r)
以下是测试部分:
if __name__ == '__main__':
solution = Solution()
#preorder_seq = [1, 2, 4, 7, 3, 5, 6, 8]
# middleorder_seq = [4, 7, 2, 1, 5, 3, 8, 6]
preorder_seq=["A","b","c","d","e","f","g"]
middleorder_seq=["g","f","e","d","c","b","A"]
treeRoot1 = solution.getBSTwithPreTin(preorder_seq, middleorder_seq)
if 1:
newArray = solution.PrintFromTopToBottom(treeRoot1)
print(newArray)
print(solution.maxDepth(treeRoot1))