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

后端 未结 5 1024
甜味超标
甜味超标 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:34

    Know I am late but the above answers have bugs that make them incomplete binary trees. Finding the correct path requires going all the way to the ancestor closest to the root rather than just looking at the parent. I changed the function quite a lot though and included info on parent in a node to illustrate.

    class CompleteTree {
        Node root;
    
    public CompleteTree() {
        root = null;
        } 
    
    void insertWrapper(int value) {
        if (root == null) root = new Node(value);
            else insert(root,new Node(value));
        }
    
    void insert(Node root, Node newnode) {
        if (((newnode.value - 1) / 2) == root.value) {
           if (root.left == null) {
                newnode.parent = root;              
                root.left = newnode;
           }
           else {
                newnode.parent = root;
                root.right = newnode;
           }
        }
        else {
           //goal to get ancestor 1 level under root to base the decision which subtree to go next
           int ancestor = parent;
           while (((ancestor - 1) / 2) > root.value) {
               ancestor = (ancestor - 1) / 2;
           }
           root = ((ancestor%2)==1) ? root.left : root.right;
           insert(root,newnode);
        }
        }
    
    
    void printInorder(Node root) {
        if (root == null) return;
        printInorder(root.left);
        System.out.print("Hi, i am "+root.value+" and my parent is ");
        if (root.parent == null) System.out.println ("NULL");
            else System.out.println(root.parent.value);
        printInorder(root.right);
        }
    }
    
    class Node {
        int value;
        Node left;
        Node right;
        Node parent;
    
    public Node (int value) {
        this.value = value;
        left = null;
        right = null;
        parent = null;
        }
    
    public Node (int value, Node parent) {
        this.value = value;
        left = null;
        right = null;
        this.parent = parent;
        }
    }
    

    Test:

    public static void main (String[] args) throws java.lang.Exception
    {
        CompleteTree b = new CompleteTree();
        for (int i=0; i<10; i++) {
            b.insertWrapper(i);
        }
        b.printInorder(b.root);
    }
    

    I think the above answers failed insertion starting with no 9.

提交回复
热议问题