outprintcurval ifcurrightnull inordercurright public static void mainString

Outprintcurval ifcurrightnull inordercurright public

This preview shows page 2 - 4 out of 4 pages.

System.out.print(cur.val+" "); if(cur.right!=null) inorder(cur.right); } public static void main(String[] args) { DeleteNodeinaBST s = new DeleteNodeinaBST(); /*case1, node to be deleted is a leaf * just delete the node * 50 50 / \ delete(20) / \ 30 70 ---------> 30 70
Image of page 2
/ \ / \ \ / \ 20 40 60 80 40 60 80 * * */ // TreeNode root = new TreeNode(50); // TreeNode node1 = new TreeNode(30); // TreeNode node2 = new TreeNode(70); // TreeNode node3 = new TreeNode(20); // TreeNode node4 = new TreeNode(40); // TreeNode node5 = new TreeNode(60); // TreeNode node6 = new TreeNode(80); // // root.left = node1; // root.right = node2; // node1.left = node3; // node1.right = node4; // node2.left = node5; // node2.right = node6; // // TreeNode node= s.deleteNode(root,20 ); // s.inorder(node); /*case2, node to be deleted has one child * copy the value of child to the node, then delete child node * 50 50 / \ delete(30) / \ 30 70 ---------> 40 70 \ / \ / \ 40 60 80 60 80 * * */ /* TreeNode root = new TreeNode(50); TreeNode node1 = new TreeNode(30); TreeNode node2 = new TreeNode(70); TreeNode node3 = new TreeNode(40); TreeNode node4 = new TreeNode(60); TreeNode node5 = new TreeNode(80); root.left = node1; root.right = node2; node1.right = node3; node2.left = node4; node2.right = node5; TreeNode node= s.deleteNode(root,30 ); s.inorder(node); */ /*case3, node to be deleted has two children * find inorder successor of the node, copy the contents of inorder successor to the node and then delete the inorder successor. * Note that inorder predecessor can also be used. * 10 * / \ * 6 12 * / \ \ * 3 9 18 * / \ / * 1 5 7 * \ * 8 * */
Image of page 3
TreeNode root = new TreeNode(10); TreeNode node1 = new TreeNode(6); TreeNode node2 = new TreeNode(12); TreeNode node3 = new TreeNode(3); TreeNode node4 = new TreeNode(8); TreeNode node5 = new TreeNode(18); TreeNode node6 = new TreeNode(1); TreeNode node7 = new TreeNode(5); TreeNode node8 = new TreeNode(7); root.left = node1; root.right = node2; node1.left = node3; node1.right = node4; node2.right = node5; node3.left =node6; node3.right=node7; node4.left = node8; TreeNode node= s.deleteNode(root,6 ); s.inorder(node); } }
Image of page 4

You've reached the end of your free preview.

Want to read all 4 pages?

  • Spring '16
  • Mohammed Anwaruddin

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes