一維陣列建立完全二叉樹
阿新 • • 發佈:2021-01-27
一維陣列建立完全二叉樹
python實現
// An highlighted block
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def CreateTree(completeTreeList, start):
"""
用陣列建立完全二叉樹
:param completeTreeList: list
: return: TreeNode
"""
if start >= len(completeTreeList):
return
else:
node = TreeNode(completeTreeList[start])
node.left = CreateTree(completeTreeList, start*2)
node.right = CreateTree(completeTreeList, start*2+1)
return node
def Inorder (root):
#中序遍歷
if root is None:
return
Inorder(root.left)
print(root.val)
Inorder(root.right)
if __name__ == '__main__':
l = [0, 1,2,4,3,5]
node = CreateTree(l, 1)
Inorder(node)