恒定时间内二叉搜索树的高度

编程入门 行业动态 更新时间:2024-10-11 11:22:06
本文介绍了恒定时间内二叉搜索树的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要使用O(1)的时间来精确二叉搜索树的高度我能想到的唯一方法就是检查添加和删除方法增加全局计数器是否还有其他方式?

I need to fine the height of a binary search tree with a time of O(1) the only way i could think to do this is to put a check in the add and remove methods incrementing a global counter is there any other way?

推荐答案

O(1)时间表明你应该在请求时已经有了高度。

O(1) time suggests that you should already have the height when it is requested.

最好的方法是在添加/删除新节点时保持/更新正确的值。你正在以正确的方式做到这一点,但它增加了添加和删除的复杂性。

The best way is it to keep/update the correct value whenever a new node is added/deleted . You are doing it in a right way , however it increases the complexity on addition and deletion.

你可以做多种方式,比如保持深度值和树等节点。

You can do it number of ways , like keep the depth value along with the node in tree etc.

class Node{ int depth; Object value; } Node lowestNode;

我可以考虑将最大深度节点参考存储在一个对象中并将其保持为深度。因此,无论何时添加新元素,都可以根据其父元素检查元素的深度,如果新元素具有更多深度,则替换最大深度节点。

I can think of storing the max depth node reference in an object and keep that as depth . So whenever you add a new element , you can check the depth of element based on its parent and replace the max depth node if the new element has more depth .

如果要删除最大深度节点,则将其替换为父节点,否则沿树递归校正所有元素的深度。

If you are deleting the max depth node then replace it with the parent otherwise correct the depth of all elments recursively along the tree.

树的高度是, lowestNode.depth

更多推荐

恒定时间内二叉搜索树的高度

本文发布于:2023-11-29 09:51:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646053.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间内   高度

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!