二叉树
创建和遍历
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x, left=None, right=None):
self.val = x
self.left = left
self.right = right
@staticmethod
def before(self):
"""
前序遍历 根 左 右
:param self:
:return:
"""
if not self:
return
print(self.val)
self.before(self.left)
self.before(self.right)
@staticmethod
def middle(self):
"""
中序遍历,左 根 右
:param self:
:return:
"""
if not self:
return
self.middle(self.left)
print(self.val)
self.middle(self.right)
@staticmethod
def after(self):
"""
右序遍历 左 右 根
:param self:
:return:
"""
if not self:
return
self.after(self.left)
self.after(self.right)
print(self.val)
@staticmethod
def depth(self):
"""
层次遍历
:return:
"""
if not self:
return
res, q = [],[]
# 根节点入队
q.append(self)
# 循环 q 队列
while q:
# 取出第一个元素
node = q.pop(0)
# 把节点的值加到列表
res.append(node.val)
# 如果节点的左边有节点,入队
if node.left:
q.append(node.left)
# 如果节点的右边有节点,入队
if node.right:
q.append(node.right)
return res
def __str__(self):
return self.val
root = TreeNode(
'A',
TreeNode('B',
TreeNode('D',
TreeNode('G')),
),
TreeNode('C',
TreeNode('E',
TreeNode('H')),
TreeNode('F',
right=TreeNode('I'))
)
)
# 验证
# print(root)
# print(root.left)
# print(root.right)
# print(root.left.left)
# print(root.right.left)
# root.before(root)
# root.middle(root)
root.after(root)
print(root.depth(root))