Min Chen School of Computer Science and Engineering Seoul National University Data Structure: Chapter 7
Definition of Binary Search Trees Operations for Binary Search Trees Search Insertion Deletion Definition of Trees Operations for Trees Search Insertion Deletion
Definition: a binary tree, satisfying: The left subtree of a node contains only nodes with keys less than the node's key The right subtree of a node contains only nodes with keys greater than the node's key Both the left and right subtrees must also be binary search trees
Binary Tree Node Right Child Parent Item Left Child Class BiTreeNode { Entry entry; BiTreeNode parent ; BiTreeNode leftChild; BiTreeNode rightChild; } Class BiTreeNode { Entry entry; BiTreeNode parent ; BiTreeNode leftChild; BiTreeNode rightChild; } Public Class BinaryTree { BinaryTreeNode root; int size; } Public Class BinaryTree { BinaryTreeNode root; int size; } Public Class BinaryTreeNode { Object item ; BiTreeNode parent ; BiTreeNode leftChild; BiTreeNode rightChild; public void inorder() { if(leftChild!=null){ leftChild.inorder(); } this.visit(); if(rightChild!=null) { rightChild.inorder(); } Public Class BinaryTreeNode { Object item ; BiTreeNode parent ; BiTreeNode leftChild; BiTreeNode rightChild; public void inorder() { if(leftChild!=null){ leftChild.inorder(); } this.visit(); if(rightChild!=null) { rightChild.inorder(); }
Binary Search Tree is designed for searching Search for Value 7 Start from the root 7 is smaller than 8, then left subtree Compare 7 with 3 7 is larger than 3, then right subtree Compare 7 with 6 7 is larger than 6, then right subtree 7 is found !
To find the right place to insert it Insert 45 Start from the root 45 is smaller than 60, then left subtree Compare 45 with is larger than 40, then right subtree Compare 45 with is smaller than 50, then left subtree 50 has no left child Add 45 as 50’s left child
Step 1: Search for the value to be deleted Step 2: Delete the node with the value The corresponding node has no child ▪ Delete the node directly The corresponding node has one child ▪ Delete the node ▪ Its child take the place of the deleted node The corresponding node has two children ▪ Call the node to be deleted "N". Do not delete N. Instead, choose either its in-order successor node or its in-order predecessor node, "R". Replace the value of N with the value of R, then delete R. (Note: R itself has up to one child.)