Binary Search Tree Recursive insert not displaying anything

后端 未结 3 1561
Happy的楠姐
Happy的楠姐 2021-01-21 10:36

I\'m doing a small Java work on Binary Search Tree but when I\'m implementing the recursive insert of a node into the tree and display it, I don\'t get anything. I\'ve been on i

3条回答
  •  别那么骄傲
    2021-01-21 11:05

    Your left, right element of the BSTNodes are null. You need to create them before inserting into it. Otherwise they create an empty hanging BSTNode() and insert it, without connecting to the rest of the tree.

    You can change the lines,

                if ( elem.compareTo( root.element ) < 0 ) {
                    insertR( root.left, elem );
                } else {
                    insertR( root.right, elem );
                }
    

    to

     if ( elem.compareTo( root.element ) < 0 ) {
            if ( root.left == null )
                 root.left = new BSTNode( elem );
            else
                insertR( root.left, elem );
        } else {
            if ( root.right == null )
                 root.right = new BSTNode( elem );
            else
                 insertR( root.right, elem );
        }
    

提交回复
热议问题