简体   繁体   English

AVL树:向每个节点添加新字段:树的“大小”,同时执行插入操作

[英]AVL tree : adding a new field to each node : the “size” of its tree , while Insert action

I'm trying to update the Insert action while inserting a new element into an AVL tree . 我在将新元素插入AVL树时尝试更新Insert动作。 The update to the insert action will add to each node the size of its rooted tree . insert动作的更新将为每个节点增加其根目录树的大小。

Now ,since I insert my elements bottom-up , then if I just add a +1 for every node that I pass while touring up , then in some cases this wouldn't work , for example when I need to balance the tree after the new tree is not balanced , since I change pointers , then the calculation wouldn't be correct . 现在,因为我自下而上插入了元素,所以如果我仅在巡回旅行时为通过的每个节点添加+1 ,则在某些情况下将无法正常工作,例如,当我需要在新树是不平衡的,因为我改变了指针,那么计算将是不正确的。

Any idea or hint how can I do that correctly? 任何想法或提示,我该如何正确地做到这一点?

A simple solution could be to modify it simply with the definition of the size. 一个简单的解决方案是仅通过定义大小来修改它。

Give the leaves size = 1 , and for each node that is a part of the tour to the root, or was a part of a roll (from buttom up) set: 设置叶子的size = 1 ,并为作为根之旅的一部分或作为卷的一部分(从buttom向上)的每个节点设置:

size(v) = size(v.left) + size(v.right) + 1
            ^                 ^          ^
        size of left     size of right   size of "root"
           subtree        subtree     

This will be correct because you modify in each step all the vertices that were changed, and since you do it buttom-up, the size can be calculated correctly for each node you modify. 这将是正确的,因为您在每个步骤中都修改了所有已更改的顶点,并且由于要进行自顶向下的操作,因此可以为您修改的每个节点正确计算大小。

Note that it does not affect complexity, since for each such vertex - you are doing constant number of OPs, and you are doing it only to vertices you would have traversed anyway. 请注意,它不会影响复杂性,因为对于每个这样的顶点-您执行的操作数是恒定的,并且仅对要遍历的顶点进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM