Python:樹的遍歷


各種遍歷順序如下圖所示:

樹的最大深度 

# 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM