Python:树的遍历

出处:https://www.cnblogs.com/delav/p/9693820.html

各种遍历顺序如下图所示:

树的最大深度 

复制代码

# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def maxdepth(self, root):
        if root is None:
            return 0
        return max(self.maxdepth(root.left), self.maxdepth(root.right))+1

复制代码

 

深度优先

深度优先遍历有三种方式:前序遍历、中序遍历和后序遍历

所说的前序、中序、后序,是指根节点的先后顺序。

前序遍历:根节点 -> 左子树 -> 右子树

复制代码

# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def preorder(self, root):
        if root is None:
            return ''
        print root.val
        if root.lef:
            self.preorder(root.left)
        if root.right:
            self.preorder(root.right)
            

复制代码

中序遍历:左子树 -> 根节点 -> 右子树

复制代码

# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def midorder(self, root):
        if root is None:
            return ''
        if root.lef:
            self.midorder(root.left)
        print root.val
        if root.right:
            self.midorder(root.right)

复制代码

后序遍历:左子树 -> 右子树 -> 根节点

复制代码

# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def endorder(self, root):
        if root is None:
            return ''
        if root.lef:
            self.endorder(root.left)
        if root.right:
            self.endorder(root.right)
        print root.val

复制代码

 

 广度优先

广度优先遍历,即层次遍历,优先遍历兄弟节点

层次遍历:根节点 -> 左节点 -> 右节点

复制代码

# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
  def graorder(self, root):
    if root is None:
      return ''
    queue = [root]
    while queue:
      res = []
      for item in queue:
        print item.val,
        if item.left:
          res.append(item.left)
        if item.right:
          res.apppend(item.right)
      queue = res

复制代码

 

比较两棵树是否相同

复制代码

# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def issame(self, root1, root2):
        if root1 is None and root2 is None:
            return True
        elif root1 and root2:
            return root1.val==root2.val and issame(root1.left, root2.left) and issame(root1.right, root2.right)
        else:
            return False

复制代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值