python 두 갈래 나무 귀속 총결산
25079 단어 소백 공부 노트
1. 장식기: 이 글은 잘 썼고 장식기의 실행 순서에 대해 전면적인 인식을 가지게 되었다.https://blog.csdn.net/qq_26442553/article/details/82226657 2、python build binary tree:
class BinTreeNode(object):
def __init__(self,data,left = None,right = None):
self.data = data
self.left = left
self. right = right
class Stack(object):
def __init__(self):
self.items =[]
def push(self,value):
self.items.append(value)
def pop(self):
return self.items.pop()
def isempty(self):
l = len(self.items)
if l ==0:
return True
else:
return False
class BinTree(object):
def __init__(self,root=None):
self.root = root
def preordertree(self,root):
if not isinstance(root, BinTreeNode):
return None
if root is not None:
print(root.data)
self.preordertree(root.left) # self.
self.preordertree(root.right)
def pre_order(self,root): #
stack = Stack()
while(root is not None or not stack.isempty()):
if root is not None:
print(root.data)
if root.right is not None:
stack.push(root.right)
root = root.left
else:
root = stack.pop()
def mid_order(self,root): # ,
stack = Stack()
while(root is not None or not stack.isempty()):
if root is not None:
stack.push(root)
root = root.left
else:
root = stack.pop()
print(root.data)
root = root.right
def post_order(self,root):
stack = Stack()
s =[]
while root is not None or not stack.isempty():
if root is not None:
s.append(root.data)
#print(root.data)
if root.left is not None:
stack.push(root.left)
root = root.right
else:
root = stack.pop()
return s[::-1]
def middleorder(self, root):
if root is not None:
self.middleorder(root.left)
print(root.data)
self.middleorder(root.right)
def postorder(self,root):
if root is not None:
self.postorder(root.left)
self.postorder(root.right)
print(root.data)
@classmethod
def build_bintree(cls,node_list):
node_dict ={} # , data key
for node_data in node_list:
data = node_data['data']
node_dict[data]= BinTreeNode(data)
for node_data in node_list:
data = node_data['data']
node = node_dict[data]
node.left = node_dict.get(node_data['left'])
node.right = node_dict.get(node_data['right'])
if node_data['isroot'] is True:
cls.root = node
return cls.root
if __name__ == "__main__":
s=[{'data':'A','left':'B','right':'C','isroot':True},{'data':'B','left':'D','right':'E','isroot':False},{'data':'C','left':'G','right':None,'isroot':False},{'data':'D','left':None,'right':None,'isroot':False},{'data':'E','left':'M','right':'F','isroot':False},{'data':'G','left':None,'right':None,'isroot':False},{'data':'M','left':None,'right':None,'isroot':False},{'data':'F','left':None,'right':None,'isroot':False}]
btree = BinTree()
btree.root = BinTree.build_bintree(s)
btree.postorder(btree.root)
#btree.middleorder(btree.root)
s = btree.post_order(btree.root)
print(s)
가장 토할 만한 것은 두 갈래 나무의 뒤서열이 8을 두루 훑어보았는데 오랫동안 쓰지 않았는데 갑자기 빛이 나서 이런 방법을 생각하게 되었다.히히그럼요. 진심으로 공부하는 마음으로 저는 다른 사람의 진지한 방법을 배우기로 했습니다.https://blog.csdn.net/u012877472/article/details/49401751세 번째 방법 2.https://www.cnblogs.com/rain-lei/p/3705680.html내일 이거 배워요.