二叉树的遍历(python)

普通二叉树
树的深度
深度优先遍历:前序,中序,后序遍历
广度优先遍历
两棵树是否相同

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值