剑指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

你可能感兴趣的:(python,剑指offer,实习,二叉树,递归)