How to implement a Complete Binary Tree using recursion without comparing the value of the node?

后端 未结 5 1027
甜味超标
甜味超标 2021-01-17 06:47
public void recurInsert(BinaryTree.Node root, BinaryTree.Node newNode, int height) {
    if (newNode == null) {
        System.out.println(\"InsertNode is empty, ple         


        
5条回答
  •  失恋的感觉
    2021-01-17 07:29

    Thanks to Jim's c# code and his solution. Below is the java version if anybody would like to try java.

        class BTnode 
    {
        BTnode left;
        BTnode right;
        int data;
    
        BTnode(int data) {
            this.data = data;
        }
        /**Best way to implement it*/
        void insert(BTnode root, BTnode newnode,int num){
            if (root == null) return;
            else{
                int parent = (num-1)/2;
                if( parent==0 ){
                    if (root.left == null)
                        root.left = newnode;
                    else 
                        root.right = newnode;
                }
                else {
                    root = ((parent%2)==1) ? root.left:root.right; // correct path
                    insert(root,newnode,parent);
                }
            }
        }
        //PRINT using bfs
        void bfs(BTnode root){
            LinkedList ls = new LinkedList();
            LinkedList ls1 = new LinkedList();
            LinkedList t;
            ls.addLast(root);
            while (ls.size() != 0) {
                t = ls;
                ls = ls1;
                ls1 = t;  // swap two list to get one level of all the children
                while(ls1.size()!=0) {
                    BTnode temp = ls1.poll();
                    System.out.print(temp.data+" ");
                    if(temp.left != null) 
                        ls.addLast(temp.left);
                    if(temp.right != null) 
                        ls.addLast(temp.right);
                }
                System.out.println();
            }
        }
    } 
    

提交回复
热议问题