A complete Binary Search Tree with level order insert in Java

后端 未结 2 1841
梦毁少年i
梦毁少年i 2021-01-27 16:38

We got an assignment where we need to code:

  • A Binary Search Tree
  • The Tree has to be complete, not perfect
2条回答
  •  不思量自难忘°
    2021-01-27 17:01

    I think you should do it this manner (code is in C#, but shouldn't be very hard to convert it to Java):

    //list should be sorted
    public void myFunc(List list){
            Queue> queue = new Queue>();
             queue.Enqueue(list);
    
            while(queue.Any()){
                List l = queue.Dequeue();
                int rindex = findRoot(l);
                //print r or store it somewhere
                Console.WriteLine(l.ElementAt(rindex));
                List leftlist = l.GetRange(0, rindex);
                List rightlist = l.GetRange(rindex + 1, l.Count-rindex-1);
                //leftlist = list l from index 0 to r-1; rightlist = list l from index r+1 to end.
                if (leftlist.Any())
                {
                    queue.Enqueue(leftlist);
                }
    
                if (rightlist.Any())
                {
                    queue.Enqueue(rightlist);
                }
    
            }
    
        }
    

    ******EDIT: *********************************************

    For finding the root every time you have a list of size n, do the following:

    public int findRoot(List list)
            {
                int n = list.Count;
    
                double h = Math.Ceiling(Math.Log(n + 1, 2)) - 1;
    
                double totNodesInCompleteBinaryTreeOfHeighthMinusOne = Math.Pow(2, h) - 1;
                double nodesOnLastLevel = n - totNodesInCompleteBinaryTreeOfHeighthMinusOne;
    
                double nodesOnLastLevelInRightSubtree = 0;
    
                if (nodesOnLastLevel > Math.Pow(2, h - 1))
                {
                    nodesOnLastLevelInRightSubtree = nodesOnLastLevel - Math.Pow(2, h - 1);
                }
    
                int rindex = (int)(n - nodesOnLastLevelInRightSubtree - 1 - ((totNodesInCompleteBinaryTreeOfHeighthMinusOne - 1) / 2));
    
                return rindex;
            }
    

提交回复
热议问题