剑指offer——画图让抽象问题形象化

面试题27:二叉树的镜像

  • 题目描述:

操作给定的二叉树,将其变换为源二叉树的镜像

  • 详细代码:
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    # 返回镜像树的根节点
    def Mirror(self, root):
        # write code here
        if not root:
        	return None
        if not (root.left or root.right):
        	return root
        temp = root.left
        root.left = root.right
        root.right = temp
        if root.left:
        	return self.Mirror(root.left)
        if root.right:
        	return self.Mirror(root.right)  

面试题28:对称的二叉树

  • 题目描述:

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的

  • 详细代码:
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.isSymmetricCore(root, root)

	def isSymmetricCore(self, root1, root2):
		if not (root1 or root2):
			return True
		elif not (root1 and root2):
			return False
		if root1.val != root2.val:
			return False
		return self.isSymmetricCore(root1.left, root2.right) and self.isSymmetrcCore(root1.right, root2.left)

面试题29:顺时针打印矩阵

  • 题目描述:

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

  • 详细代码:
# -*- coding:utf-8 -*-
class Solution:
    # matrix类型为二维列表,需要返回列表
    def printMatrix(self, matrix):
        # write code here
        if not matrix or len(matrix) <= 0 or len(matrix[0]) <= 0:
        	return matrix
        row = len(matrix)
        col = len(matrix[0])
        start = 0
        res = []
        while(row > start * 2 and col > start * 2):
        	self.PrintMatrixCore(matrix, row, col, start, res)
        	start += 1
        return res

	def PrintMatrixCore(self, matrix, row, col, start, res):
		endX = row - 1 - start
		endY = col - 1 - start
		for i in range(start, endY + 1):
			res.append(matrix[start][i])
		
		if endX > start:
			for i in range(start + 1, endX + 1):
				res.append(matrix[i][endY])
		
		if endX > start and endY > start:
			for i in range(endY - 1, start - 1, -1):
				res.append(matrix[endX][i])

		if endX - 1 > start and endY > start:
			for i in range(endX - 1, start, -1):
				res.append(matrix[i][start])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值