节点表示
使用结点和引用实现二叉树
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 19 22:42:32 2019
@author: 86156
"""
#二叉树的实现
class BinaryTree:
#根初始化
def __init__(self,rootobj):
self.key=rootobj
self.leftChild=None
self.rightChild=None
#插入左结点
def insertLeft(self,newNode):
if self.leftChild==None:
self.leftChild=BinaryTree(newNode)
else:
t=BinaryTree(newNode)
t.leftChild=self.leftChild
self.leftChild=t
#插入右结点
def insertRight(self,newNode):
if self.rightChild==None:
self.rightChild=BinaryTree(newNode)
else:
t=BinaryTree(newNode)
t.rightChild=self.rightChild
self.rightChild=t
#获取左子树
def getRightChild(self):
return self.rightChild
#获取右子树
def getLeftChild(self):
return self.leftChild
#设置根植
def setRootVal(self,obj):
self.key=obj
def getRootVal(self):
return self.key
r=BinaryTree('a')
print(r.getRootVal())
print(r.getLeftChild())
r.insertLeft('b')
print(r.getLeftChild())
print(r.getLeftChild().getRootVal())
r.insertRight('c')
print(r.getRightChild())
print(r.getRightChild().getRootVal)
r.getRightChild().setRootVal('hello')
print(r.getRightChild().getRootVal())
从上往下打印二叉树
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
def PrintFromTopToBottom(root):
if not root:#二叉树为空
return []
lst=[]
result=[]
lst.append(root)
while len(lst):
t=lst.pop(0)
result.append(t.val)
if t.left:
lst.append(t.left)
if t.right:
lst.append(t.right)
return result