Build a simple, high performance Tree Data Structure in c#

后端 未结 3 462
不知归路
不知归路 2020-12-04 08:56

I need to create a product catalog, in tree type.

every tree node presents by a ID(string), the functions on the tree data only 2:

  1. getChild(strin
3条回答
  •  清歌不尽
    2020-12-04 09:30

    You can write a simple binary tree , I wrote some Pseudo code beloew:

    class TreeNode {
        TreeNode Right;
        TreeNode Left;
        int id;
        //...
    }
    
    class BinTree {
    
        void Insert(TreeNode node)
        {
            while(true) {   
                if(node.id > target.id) {
                    if(target.Right != null) {
                        target = target.Right;
                        continue;
                    }
                    else {
                        target.Right = node;
                        break;
                    }
                }
    
                else if(node.id < target.id) {
                    if(target.Left != null) {
                        target = target.Left;
                        continue;
                    }
                    else {
                        target.Left = node;
                        break;
                    }   
                }
    
                else {
                    throw new ArgumentException("Duplicated id");
                }
            }
        }
    
    
        TreeNode Search(int id)
        {
            TreeNode target = root;
    
            while(target != null) {
                if(id > target.id) {
                    target = target.Right;
                }
                else if(id < target.id) {
                    target = target.Left;
                }
                else {
                    return target;
                }
            }
    
            return null;
        }
    
    }
    

    But if your data count is very large, maybe AVL tree is more efficient

提交回复
热议问题