面试练习题汇总
  • 说明
  • C/C++ 问答题汇总
  • 编程题汇总
    • 腾讯 2017 暑期实习生编程题
      • 构造回文
      • 算法基础-字符移位
      • 有趣的数字
    • 剑指 Offer 编程题练习
      • 二维数组中的查找
      • 从尾到头打印链表
      • 旋转数组的最小数字
      • 替换空格
      • 用两个栈实现队列
      • 重建二叉树
    • 网易 2017 校招笔试编程题
      • 二进制权重
      • 平方串
      • 数位和
  • 安全测试开发相关面试
    • 安全测试类面试参考
    • 业务安全类面试参考
    • 测试开发类面试参考
  • 深信服sangfor相关
    • 深信服acm相关
    • 测试类面试参考
    • 智安全杯
      • 智安全杯-2018比赛
      • 智安全杯-2019初赛
      • 智安全杯-2019复赛
  • 软件测试题汇总
  • 计算机知识题汇总
    • 前 75 题
    • 75 题以后
  • Python 语言特性
    • 1 Python的函数参数传递
    • 2 @staticmethod和@classmethod
    • 3 类变量和实例变量
    • 4 Python中单下划线和双下划线
    • 5 args and *kwargs
    • 6 面向切面编程AOP和装饰器
    • 7 单例模式
    • 8 Python 函数式编程
    • 9 Python 里的拷贝
  • stackoverflow-about-Python
    • Python中关键字yield有什么作用?
    • [Python中的元类(metaclass)是什么?](stackoverflow-about-Python/Python中的元类(metaclass)是什么.md)
    • Python中如何在一个函数中加入多个装饰器?
    • 如何判断一个文件是否存在?
    • 如何调用外部命令?
    • 枚举类型的使用?
    • 在Windows下安装pip?
    • 字典合并问题
    • 在Android上运行Python
    • 根据字典值进行排序
    • 在函数里使用全局变量
    • 变化的默认参数
    • 装饰器classmethod和staticmethod的区别
    • 检查列表为空的最好办法
    • 怎么用引用来改变一个变量
    • 检查文件夹是否存在的操作
    • name=main的作用
    • super与init方法
    • str与repr的区别
    • 循环中获取索引
    • 类里的静态变量
    • 怎么在终端里输出颜色?
    • 为什么用pip比用easy_install的好?
    • join的问题
    • 把列表分割成同样大小的块
    • 为什么代码在一个函数里运行的更快
    • 如何快速合并列表中的列表?
    • 如何知道一个对象有一个特定的属性?
    • 如何通过函数名的字符串来调用这个函数?
    • 单下划线和双下划线的含义?
  • Python 面试编程题
    • 1 台阶问题 斐波那契
    • 2 变态台阶问题
    • 3 矩形覆盖
    • 4 杨氏矩阵查找
    • 5 去除列表中的重复元素
    • 6 链表成对调换
    • 7 创建字典的方法
    • 8 合并两个有序列表
    • 9 二分查找
    • 10 快排
    • 11 找零问题
    • 12 二叉树相关
    • 13 单链表逆置
Powered by GitBook
On this page
  • 题目
  • binary_tree.py

Was this helpful?

  1. Python 面试编程题

12 二叉树相关

题目

实现二叉树的相关算法

binary_tree.py

#!/bin/env python3
# -*- coding: utf-8 -*-
# version: Python3.X
""" 给定一个数组, 构建二叉树, 并且按层次打印这个二叉树, 以及进行深度遍历
"""
import queue
from functools import wraps

__author__ = '__L1n__w@tch'


def decorator_with_argument(sentence):
    """
    带有一个参数的修饰器
    :param sentence: 要打印的句子
    :return: 修饰器
    """

    def decorator(function):
        @wraps(function)
        def wrap(*args):
            print(sentence)
            result = function(*args)
            print("")
            return result  # 注意需要返回结果的

        return wrap

    return decorator


class Node:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right


@decorator_with_argument("第一种层次遍历")
def layer_search(root):
    """
    层次遍历
    :param root: 根节点
    :return: None
    """
    stack = [root]
    while stack:
        current = stack.pop(0)
        print(current.data, end=" ")
        if current.left:
            stack.append(current.left)
        if current.right:
            stack.append(current.right)


@decorator_with_argument("第二种层次遍历")
def layer_order_traverse(root):
    """
    层次遍历第二种写法, 其实就换了个数据结构
    :param root: 根节点
    :return: None
    """
    a_queue = queue.Queue()
    a_queue.put(root)
    while not a_queue.empty():
        node = a_queue.get()
        print(node.data, end=" ")
        if node.left:
            a_queue.put(node.left)
        if node.right:
            a_queue.put(node.right)


@decorator_with_argument("先序遍历")
def pre_order_traverse(root):
    """
    深度遍历, 先序遍历?
    PS: 之所以把递归封装起来是为了不重复调用装饰器
    :param root: 根节点
    :return: None
    """

    def __recursion(node):
        if not node:
            return None
        print(node.data, end=" ")
        __recursion(node.left)
        __recursion(node.right)

    return __recursion(root)


@decorator_with_argument("中序遍历")
def in_order_traverse(root):
    """
    中序遍历
    :param root: 根节点
    :return: None
    """

    def __recursion(node):
        if not node:
            return None
        if node.left:
            __recursion(node.left)
        print(node.data, end=" ")
        if node.right:
            __recursion(node.right)

    return __recursion(root)


@decorator_with_argument("后序遍历")
def post_order_traverse(root):
    """
    后序遍历
    :param root: 根节点
    :return: None
    """

    def __recursion(node):
        if not node:
            return None
        if node.left:
            __recursion(node.left)
        if node.right:
            __recursion(node.right)
        print(node.data, end=" ")

    return __recursion(root)


@decorator_with_argument("求最大树深")
def max_depth(root):
    """
    求树的最大深度
    :param root: 根节点
    :return: int()
    """

    def __recursion(node):
        if not node:
            return 0
        return max(__recursion(node.left), __recursion(node.right)) + 1

    return __recursion(root)


@decorator_with_argument("判断两棵树是否相同")
def is_same_tree(root1, root2):
    """
    递归判断两颗树是否相同
    :param root1: 根节点 1
    :param root2: 根节点 2
    :return: True or False
    """

    def __recursion(node1, node2):
        if node1 is None and node2 is None:
            return True
        elif node1 and node2:
            return node1.data == node2.data \
                   and __recursion(node1.left, node2.left) \
                   and __recursion(node1.right, node2.right)
        else:
            return False

    return __recursion(root1, root2)


@decorator_with_argument("先序中序创建二叉树")
def create_binary_tree_by_pre_in_order(pre_order_list, in_order_list):
    """
    根据先序中序创建二叉树
    :param pre_order_list: [1, 3, 7, 0, 6, 2, 5, 4]
    :param in_order_list: [0, 7, 3, 6, 1, 5, 2, 4]
    :return: Node() or None
    """

    def __recursion(pre_order, in_order):
        if not pre_order:
            return None
        current = Node(pre_order[0])
        index = in_order.index(pre_order[0])
        current.left = __recursion(pre_order[1:index + 1], in_order[:index])
        current.right = __recursion(pre_order[index + 1:], in_order[index + 1:])
        return current

    return __recursion(pre_order_list, in_order_list)


@decorator_with_argument("中序后序创建二叉树")
def create_binary_tree_by_post_in_order(post_order_list, in_order_list):
    """
    根据中序后序来创建二叉树
    :param post_order_list: [0, 7, 6, 3, 5, 4, 2, 1]
    :param in_order_list: [0, 7, 3, 6, 1, 5, 2, 4]
    :return: Node() or None
    """

    def __recursion(post_order, in_order):
        if not post_order:
            return None
        current = Node(post_order[-1])
        index = in_order.index(post_order[-1])
        current.left = __recursion(post_order[:index], in_order[:index])
        current.right = __recursion(post_order[index:-1], in_order[index + 1:])

        return current

    return __recursion(post_order_list, in_order_list)


if __name__ == "__main__":
    tree = Node(1, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5), Node(4)))
    layer_search(tree)
    layer_order_traverse(tree)
    pre_order_traverse(tree)
    in_order_traverse(tree)
    post_order_traverse(tree)
    print(max_depth(tree))

    tree2 = Node(11, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5), Node(4)))
    print(is_same_tree(tree, tree2))

    pre_order_visit = [1, 3, 7, 0, 6, 2, 5, 4]
    in_order_visit = [0, 7, 3, 6, 1, 5, 2, 4]
    tree = create_binary_tree_by_pre_in_order(pre_order_visit, in_order_visit)
    post_order_traverse(tree)

    post_order_visit = [0, 7, 6, 3, 5, 4, 2, 1]
    tree = create_binary_tree_by_post_in_order(post_order_visit, in_order_visit)
    pre_order_traverse(tree)
Previous11 找零问题Next13 单链表逆置

Last updated 5 years ago

Was this helpful?