普通二叉树
树的深度
深度优先遍历:前序,中序,后序遍历
广度优先遍历
两棵树是否相同
class TreeNode(object):
def __init__(self,x):
self.val=x
self.right=None
self.left=None
#树的深度
def depth_tree(root):
if root==None:
return 0
return max(depth_tree(root.right),depth_tree(root.left))+1
#深度优先遍历
pre=[]
def preorder(root):
if root:pre.append(root.val)
if root.left:preorder(root.left)
if root.right:preorder(root.right)
# 非递归
def preOrderTravese(node):
stack = [node]
while len(stack) > 0:
print(node.val)
if node.right is not None:
stack.append(node.right)
if node.left is not None:
stack.append(node.left)
node = stack.pop()
mid=[]
def midorder(root):
if root.left:midorder(root.left)
if root:mid.append(root.val)
if root.right: midorder(root.right)
# 非递归
def midOrderTravese(node):
stack = []
pos = node
while pos is not None or len(stack) > 0:
if pos is not None:
stack.append(pos)
pos = pos.left
else:
pos = stack.pop()
print(pos.val)
pos = pos.right
end=[]
def endorder(root):
if root.left:midorder(root.left)
if root.right: midorder(root.right)
if root: end.append(root.val)
# 非递归
# 使用两个栈结构
# 第一个栈进栈顺序:左节点->右节点->跟节点
# 第一个栈弹出顺序: 跟节点->右节点->左节点(先序遍历栈弹出顺序:跟->左->右)
# 第二个栈存储为第一个栈的每个弹出依次进栈
# 最后第二个栈依次出栈
def postOrderTraverse(node):
stack = [node]
stack2 = []
while len(stack) > 0:
node = stack.pop()
stack2.append(node)
if node.left is not None:
stack.append(node.left)
if node.right is not None:
stack.append(node.right)
while len(stack2) > 0:
print(stack2.pop().val)
#广度优先遍历
def breadth_first(root):
queue=[]
result=[]
if root:queue.append(root)
while queue:
res=[]
for i in queue:
result.append(i.val)
if i.left:res.append(i.left)
if i.right:res.append(i.right)
queue=res
return result
# 比较两棵树是否相同
def is_Same(root1,root2):
if root1==None and root2==None:
return True
if root1==None or root2==None:
return False
return root1.val==root2.val and is_Same(root1.left,root2.left) and is_Same(root1.right,root2.right)