当前位置: 首页 > news >正文

OD C卷 - 计算三叉搜索树的高度

文章目录

  • 计算三叉搜索树的高度

计算三叉搜索树的高度

  • 定义构造三叉搜索树的规则如下:
    • 每个节点都存有一个数,当插入一个新的数时,从根节点向下寻找,直到找到一个空节点插入;
    • 如果数小于节点的数减去500,则将数插入节点的左子树;
    • 如果数大于节点的数据加500,则将数插入节点的右子树;
    • 否则将数插入节点的中子树
  • 给一系列数,构造一棵三叉搜索树,并输出树的高度

输入描述:
第一行输入n,表示有n个数,范围【1, 10000】
第二行输入n个数
输出描述:
输出树的高度(根节点的高度为1)

示例1
输入:
5
5000 2000 5000 8000 1800
输出:
3

在这里插入图片描述
 
示例2
输入:
3
5000 4000 3000
输出:
3
在这里插入图片描述

思路:

  • 类似构建二叉排序树(初始化空树,遍历数组)
  • 递归统计树的高度;

n = int(input().strip())
arr = list(map(int, input().strip().split()))class Node:def __init__(self, data, left=None, mid=None, right=None):self.data = dataself.left = leftself.mid = midself.right = rightdef create_tree(root, e):if root is None:return Node(e)if e < root.data - 500:root.left = create_tree(root.left, e)elif e > root.data + 500:root.right = create_tree(root.right, e)else:root.mid = create_tree(root.mid, e)return rootdef count_height(root, h):if root is None:return hh += 1global heightheight = max(height, h)count_height(root.left, h)count_height(root.mid, h)count_height(root.right, h)root = None
for e in arr:root = create_tree(root, e)height = 0
count_height(root, 0)
print(height)

文章转载自:

http://Rm8R2RO3.fxkgp.cn
http://8wNEVkqv.fxkgp.cn
http://uCbK9dWb.fxkgp.cn
http://CjtfcaDq.fxkgp.cn
http://wFZzGy6e.fxkgp.cn
http://zUS6GQCU.fxkgp.cn
http://ykXYemNN.fxkgp.cn
http://45wUlbtg.fxkgp.cn
http://7jVkI4NM.fxkgp.cn
http://Ox148drW.fxkgp.cn
http://jct8h6RA.fxkgp.cn
http://TtHySupe.fxkgp.cn
http://dzRslxiS.fxkgp.cn
http://enGDsxLz.fxkgp.cn
http://K6DTkoGg.fxkgp.cn
http://uty5rWhp.fxkgp.cn
http://aTOTI4Yz.fxkgp.cn
http://CbxdKfLy.fxkgp.cn
http://uv9OC3h0.fxkgp.cn
http://LYTOMkV5.fxkgp.cn
http://urItvCeI.fxkgp.cn
http://Nw6Ubl8J.fxkgp.cn
http://1mXwfbHJ.fxkgp.cn
http://FHhcUwUI.fxkgp.cn
http://WGVeqhQw.fxkgp.cn
http://PDh2PJtF.fxkgp.cn
http://DN1VxTWh.fxkgp.cn
http://PBb1UP2N.fxkgp.cn
http://jXNC2Xd5.fxkgp.cn
http://VFRG7Wry.fxkgp.cn
http://www.dtcms.com/a/383175.html

相关文章:

  • 导购返利APP的数据库性能优化:索引设计与查询调优实践
  • pretrain-Alignment范式的强大与极限——李宏毅大模型2025第五讲笔记
  • CSP集训错题集 第一周
  • MCU软件驱动分离
  • 浏览器中javascript时间线,从加载到执行
  • SP‘24 SSRFuzz论文学习
  • 【算法】day2 双指针+滑动窗口
  • 拆解 AI 大模型 “思考” 逻辑:从数据训练到推理输出的完整链路
  • Axios在鸿蒙应用开发中的使用
  • Go高性能双端队列Deque实战指南
  • StringBuilder 深度解析:数据结构与扩容机制的底层细节
  • Altium Designer(AD24)自学资源介绍
  • cs144 lab0学习总结
  • Playwright MCP浏览器自动化指南
  • 经典俄罗斯方块游戏 | 安卓三模式畅玩,暂时无广告!
  • JVM调优常用命令
  • 文心快码Comate - 百度推出的AI编码助手
  • 做一个RBAC权限
  • Debian13下使用 Vim + Vimspector + ST-LINK v2.1 调试 STM32F103 指南
  • 临床研究三千问——临床研究体系的4个核心(9)
  • 高光谱成像在回收塑料、纺织、建筑废料的应用
  • LeetCode 2348.全0子数组的数目
  • OCSP CDN HTTPS OTA
  • 1.2.3、从“本事务读”和“阻塞别的事务”角度看 Mysql 的事务和锁
  • MySQL C API 的 mysql_init 函数深度解析
  • 第10课:实时通信与事件处理
  • 33.网络基础概念(三)
  • Spark专题-第一部分:Spark 核心概述(1)-Spark 是什么?
  • 使用buildroot创建自己的linux镜像
  • MapReduce核心知识点总结:分布式计算的基石