# encoding=utf-8
class node(object):
def __init__(self,data,left=None,right=None):
self.data = data
self.left = left
self.right = right
tree = node('D',node('B',node('A'),node('C')),node('E',right=node('G',node('F'))))
# 先序
def front(tree):
if tree == None:
return
print(tree.data)
front(tree.left)
front(tree.right)
def front_not(tree):
if tree == None:
return
stack = []
node = tree
while node or stack:
while node:
print(node.data)
stack.append(node)
node = node.left
node = stack.pop()
node = node.right
# 中序遍历
def mid(tree):
if tree == None:
return
mid(tree.left)
print(tree.data)
mid(tree.right)
def mid_not(tree):
if tree == None:
return
stack = []
node = tree
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
print(node.data)
node = node.right
# 后序遍历
def post(tree):
if tree == None:
return
post(tree.left)
post(tree.right)
print(tree.data)
def post_not(tree):
if tree == None:
return
stack1 = []
stack2 = []
node = tree
stack1.append(node)
while stack1:
node = stack1.pop()
if node.left:
stack1.append(node.left)
if node.right:
stack1.append(node.right)
stack2.append(node)
while stack2:
print(stack2.pop().data)
# 队列
def leval(tree):
if tree == None:
return
queue = []
node = tree
queue.append(node)
while queue:
node = queue.pop(0)
print(node.data)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# deep二叉树深度
def deepth(tree):
if tree == None:
return 0
left = deepth(tree.left)
right = deepth(tree.right)
return max(left,right)+1
# print(deepth(tree))
# 节点数
def jiedian(tree):
if tree == None:
return 0
return jiedian(tree.left)+jiedian(tree.right)+1
# print(jiedian(tree))
# 叶子节点
def leaf(tree):
if tree == None:
return 0
if tree.left == None and tree.right == None:
return 1
return leaf(tree.left)+leaf(tree.right)
print(leaf(tree))