java - Binary Tree Deleting a node -
below code wrote case when deleteitem @ leaf node. if equating found leaf node "null" when print inorder traversing order if tree, element not deleted , comes on screen. missing?
public void deletenode(t deleteitem) { treenode<t> node = root; if(root == null) { system.out.print("binary tree not exist"); system.exit(0); } while((node.data != deleteitem) && (node.leftnode != null || node.rightnode != null)) { if(deleteitem.compareto(node.data)<0) node = node.leftnode; else node = node.rightnode; } //system.out.printf("deleting item is: %s\n", node.data); if(node.data != deleteitem) { system.out.println("\ndeleteitem not found in tree"); system.exit(0); } else { if(node.leftnode == null && node.rightnode == null) { node = null; } } }
java "pass-by-value", treenode<t> tmp = root
here means assigning tmp
's references root
means have 2 different references same instance. according when node = null
set local references null
means node's parent still reference it. remove leaf node tree need keep track of parent , removing reference node (removed reference in tree not local copy) that:
public void deletenode(t deleteitem) { treenode<t> node = root; treenode<t> parent = null; // parent of deleted node. if(root == null) { system.out.print("binary tree not exist"); system.exit(0); } while((node.data != deleteitem) && (node.leftnode != null || node.rightnode != null)) { parent = node; // keep track of parent of deleted node if(deleteitem.compareto(node.data) < 0) node = node.leftnode; else node = node.rightnode; } if(node.data != deleteitem) { system.out.println("\ndeleteitem not found in tree"); system.exit(0); } else { if(parent.leftnode == node) parent.leftnode = null; else parent.rightnode = null; } }
Comments
Post a Comment