劍指offer - 題58,59(對稱二叉樹遞歸,之字形打印二叉樹)

對稱的二叉樹
請實現一個函數,用來判斷一顆二叉樹是不是對稱的。注意,如果一個二叉樹同此二叉樹的鏡像是同樣的,定義其爲對稱的。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def isSymmetrical(self, pRoot):
        # write code here
        if not pRoot:
            return True
        return self.isSym(pRoot.left, pRoot.right)
    
    def isSym(self,left,right):
        if not left and not right:
            return True
        elif not left or not right:
            return False
        return left.val ==right.val and self.isSym(left.left, right.right) and self.isSym(left.right, right.left)

按之字形順序打印二叉樹
請實現一個函數按照之字形打印二叉樹,即第一行按照從左到右的順序打印,第二層按照從右至左的順序打印,第三行按照從左到右的順序打印,其他行以此類推。

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        result = []
        node_list = [pRoot]
        row = 1
        while node_list != []:
            child_list = []
            row_list = []
            for i in node_list:
                row_list.append(i.val)
                if i.left != None:
                    child_list.append(i.left)
                if i.right != None:
                    child_list.append(i.right)
            node_list = child_list
            if row %2 == 0:
                row_list.reverse()
            result.append(row_list)
            row += 1
        return result
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章