简体   繁体   中英

How to assign unique numbers to the tree nodes so that from the tree leaf I can trace back the parents?

I have to structure certain data and tree data structure suited the requirement.
I have to assign certain number to each node in such a manner that I can trace back the parent from its number. I am planning to use hashtable to store these numbers as keys, so there cannot be any duplicate value.

eg

parent - 000001
child1 - 000011
innerchild1 - 000111 (level 2, get 2 bits from right and we can reach parent)
innerchild2 - 000211
child2 - 000021
innerchild1 - 000121
innerchild2 - 000221

Depending on the level, I can mask certain bits and I can uniquely identify the parent. But if my tree grows wider(ie more parents, numbers will duplicate) How to overcome this problem?

I'd advice you to use numbers with digits 1-9.

Why no-0? 9-digit number with leading 0 looks as 8-digit on without leading 0. It will cause errors.

Thus, till any parent has maximally 9 children, the structure will suffice.

number 0 - common root
1-9 - first children
11-19 - second generation children of the first child...
and so on

If you'll have nodes with more than 9 digits, use 100-base arithmetic. (allowed digits will be 10-99). Are 99 children enough? If not, use 100-999.

Nested set tree can be used yo solve the problem. Please refer to the book below. Its an amazing book, which also contain text on Nested Set trees.

http://www.elsevier.com/wps/find/bookdescription.cws_home/702605/description

Your approach of assigning "special" numbers to nodes sounds like a bad one - likely to lead to a lot of hard work, scalability limitations and most of all... bugs.

If you need to know what the parent node is, store a reference to the parent node in a field of the node!

I don't think a "well defined" number as key is good enough.

You need design a tree structure for your requirement or at least a Node class to get parentId/parent Node easier.

for example

Node{
 id, #could be string, number, unique
 actualNode # you node value
 parentId (or Node parentNode )
}

if you would stick to hashtable for some reason, you can still use the node.id as key. there are a number of ways to generate unique string, numbers. eg current nano-seconds ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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