+ All Categories
Home > Documents > Week16 Trees

Week16 Trees

Date post: 06-Apr-2018
Category:
Upload: dylan-gray
View: 225 times
Download: 0 times
Share this document with a friend

of 43

Transcript
  • 8/3/2019 Week16 Trees

    1/43

    1

    Week 16Introduction to Trees and BSTs

  • 8/3/2019 Week16 Trees

    2/43

    2

    Terminology A tree is a collection ofnodes and directed edges, satisfying

    the following properties:

    There is one specially designated node called the root,

    which has no edges pointing to it. Every node except the roothas exactly one edge pointing

    to it.

    There is a unique path (of nodes and edges) from the root

    to each node.

    Each item can have multiple successors

    All items have exactly one predecessor.

    Except the root

  • 8/3/2019 Week16 Trees

    3/43

    3

    Graphical Representation

    Trees, as defined on the preceding slide, are typicallydrawn with circles (or rectangles) representing the nodes

    and arrows representing the edges.

    The rootis typically placed at the top of the diagram, withthe rest of the tree below it.

    Trees: Not Trees:

    root

    edge

    node

  • 8/3/2019 Week16 Trees

    4/43

    4

    Terminology (Contd.)

    If an edge goes from node a to node b, then a is called the

    parent ofb, and b is called a childofa.

    Children of the same parent are called siblings. If there is a path from a to b, then a is called an ancestor of

    b, and b is called a descendent ofa.

    A node with all of its descendants is called a subtree.

    If a node has no children, then it is called a leafof the tree. If a node has no parent (there will be exactly one of these),

    then it is the root of the tree.

  • 8/3/2019 Week16 Trees

    5/43

    5

    Terminology:Example

    A

    B C

    D EF

    G H

    I

    J K

    A is the root

    D, E, G, H, J & K

    are leaves

    B is the parentof

    D, E & F

    D, E & F are

    siblings and

    children of B

    I, J & K are

    descendants of B

    A & B are

    ancestors of I

    subtree

  • 8/3/2019 Week16 Trees

    6/43

    6

    Binary Trees

    General trees: Trees with no restrictions on number of children Intuitively, a binary tree is LIKE a general tree in which each

    node has no more than two children.

    Formally, a binary tree is a set Tof nodes such that either:

    Tis empty, or

    Tconsists of a single node, r, called the root, and two (non-overlapping) binary trees, called the leftand right subtrees

    ofr.

    Binary trees may be empty, and they distinguish between leftand right subtrees.

    (These two binary

    trees are distinct.)

  • 8/3/2019 Week16 Trees

    7/43

    7

    Terminology (Contd.)

    Childand parent

    Every node except the root has one parent

    A node can have an arbitrary number of

    children

    Leaves

    Nodes with no children

    Sibling nodes with same parent

  • 8/3/2019 Week16 Trees

    8/43

    8

    Terminology (Contd.)

    Path Length

    number of edges on the path

    Depth of a node

    length of the unique path from the root to that node

    The depth of a tree is equal to the depth of the deepest leaf

    Height of a node

    length of the longest path from that node to a leaf

    all leaves are at height 0

    The height of a tree is equal to the height of the root

    Ancestor and descendant

    Proper ancestorand proper descendant

  • 8/3/2019 Week16 Trees

    9/43

    9

    Terminology (Contd.)

    A binary tree is balanced if the difference in height

    between any nodes left and right subtree is 1.

    Note that:

    A full binary tree is also complete. A complete binary tree is not always full.

    Full and complete binary trees are also balanced.

    Balanced binary trees are not always full or complete.

  • 8/3/2019 Week16 Trees

    10/43

    Terminology (Contd.)

    10

  • 8/3/2019 Week16 Trees

    11/43

    11

    Traversing a Binary Tree

    Preorder

    Inorder

    Postorder

  • 8/3/2019 Week16 Trees

    12/43

    12

    PreorderTraversal of a Binary Tree

    Basic Idea:

    1) Visit the root.

    2) Recursively invoke preorder on the left subtree.

    3) Recursively invoke preorder on the right subtree.

  • 8/3/2019 Week16 Trees

    13/43

    13

    PreorderTraversal of a Binary Tree

    PreorderResult: 60, 20, 10, 40, 30, 50, 70

    60

    4010

    7020

    30 50

    1

    4

    5

    3

    2 7

    6

  • 8/3/2019 Week16 Trees

    14/43

    14

    InorderTraversal of a Binary Tree

    Basic Idea:

    1) Recursively invoke inorder on the left subtree.

    2) Visit the root.

    3) Recursively invoke inorder on the right subtree.

  • 8/3/2019 Week16 Trees

    15/43

    15

    InorderTraversal of a Binary Tree

    InorderResult: 10, 20, 30, 40, 50, 60, 70

    60

    4010

    7020

    30 50

    1

    4

    5

    3

    2 7

    6

  • 8/3/2019 Week16 Trees

    16/43

    16

    PostorderTraversal of a Binary Tree

    Basic Idea:

    1) Recursively invoke postorder on the left subtree.

    2) Recursively invoke postorder on the right subtree.

    3) Visit the root.

  • 8/3/2019 Week16 Trees

    17/43

    17

    PostorderTraversal of a Binary Tree

    PostorderResult: 10, 30, 50, 40, 20, 70, 60

    60

    4010

    7020

    30 50

    1

    4

    5

    3

    2 7

    6

  • 8/3/2019 Week16 Trees

    18/43

    18

    Binary Search Trees

    A binary search tree is a binary tree in which each node, n,has a value satisfying the following property

    For every node X, all the keys in its left subtree aresmaller than the key value in X, and all the keys in its

    right subtree are larger than or equal to the key value inX

    John

    PeterBrenda

    Amy Mary Tom

    21

    2

    3

    55

    34

    135

    8

  • 8/3/2019 Week16 Trees

    19/43

    19

    Searching BST

    If we are searching for 15, then we are done. If we are searching for a key < 15, then we should search in the

    left subtree.

    If we are searching for a key > 15, then we should search in theright subtree.

    Time complexity

    O(height of the tree)

  • 8/3/2019 Week16 Trees

    20/43

    20

    Inorder traversal of BST Print out all the keys in sorted order

    Inorder: 2, 3, 4, 6, 7, 9, 13, 15, 17, 18, 20

  • 8/3/2019 Week16 Trees

    21/43

    21

    findMin/ findMax

    Return the node containing the smallest element inthe tree

    Start at the root and go left as long as there is a

    left child. The stopping point is the smallest

    element Similarly for findMax

    Time complexity = O(height of the tree)

  • 8/3/2019 Week16 Trees

    22/43

    22

    findMaxfindMin

  • 8/3/2019 Week16 Trees

    23/43

    23

    Insert 13

    Proceed down the tree as you would with a Search

    If X is found or X is greater than the value in thenode visited, take the right path

    If X is smaller than the value in the node visited

    We continue until we come to an empty node, thenwe insert X

    Time complexity = O(height of the tree)

  • 8/3/2019 Week16 Trees

    24/43

    24

    delete

    When we delete a node, we need to consider how we take

    care of the children of the deleted node.

    This has to be done such that the property of the searchtree is maintained.

  • 8/3/2019 Week16 Trees

    25/43

    25

    First CaseThe node is a leaf

    Delete it

    immediately

  • 8/3/2019 Week16 Trees

    26/43

    26

    Second CaseThe node has one child

    Adjust a pointer from

    the parent to bypass that

    node

  • 8/3/2019 Week16 Trees

    27/43

    27

    Third Case

    The node has 2 childrenReplace the key of that node with the minimum

    element in the right subtree (InOrder Successor)

    OR with the maximum element in the left subtree

    (Logical Predecessor)Delete the minimum element which would have

    either no child or only one child (right child for

    InOrder Successor because if it has a left child,

    that left child would be smaller and would have

    been chosen).

    Now apply the same steps as for First Case or

    Second Case.

  • 8/3/2019 Week16 Trees

    28/43

    28

    Deleting 6

    Replace with 4 (Logical

    Predecessor) or 7

    (InOrder Successor)

  • 8/3/2019 Week16 Trees

    29/43

    29

    Binary Search Tree Implementationclass BSTNode {

    private int value;

    private BSTNode left;

    private BSTNode right;

    public BSTNode() {

    value=0;

    left = null;right = null;

    }

    public BSTNode (int x) {

    value = x;

    left = null;

    right = null;

    }

    //next slide

  • 8/3/2019 Week16 Trees

    30/43

    void set_value(int x) {

    value=x;

    }

    int get_value() {

    return value;

    }

    void set_left(BSTNode l) {

    left=l;

    }

    //next slide

    30

  • 8/3/2019 Week16 Trees

    31/43

    BSTNode get_left() {

    return left;}

    void set_right(BSTNode r){

    right=r;}

    BSTNode get_right() {

    return right;}

    } //End BSTNode

    31

  • 8/3/2019 Week16 Trees

    32/43

    public class BST {

    BSTNode root;

    public BST() {

    root=null;

    }

    public BSTNode get_root() {

    return root;

    }

    32

  • 8/3/2019 Week16 Trees

    33/43

    public void InsertElement (int x) {

    // x points to root of a subtree

    BSTNode temp=new BSTNode(x);

    if (root==null)root=temp;

    else

    {

    BSTNode P, T;

    P=T=root;

    while(T!=null)

    {

    P=T;

    if(x

  • 8/3/2019 Week16 Trees

    34/43

    public BSTNode SearchElement (int x) {

    BSTNode T;

    T=root;while((T!=null)&&(T.get_value()!=x)) {

    if(x

  • 8/3/2019 Week16 Trees

    35/43

    public void deleteElement(int K)

    // T is the node to be removed and

    // P is the parent of T.

    {

    BSTNode T=root;

    BSTNode P=root;

    BSTNode temp;

    BSTNode x, f, s;x=f=s=null;

    while((T!=null)&&(T.get_value()!=K))

    {

    P=T;

    if(K

  • 8/3/2019 Week16 Trees

    36/43

    temp=T;

    // Set x to the node that will replace T;

    // First two cases: Case of no children or one child

    if (T==null)

    System.out.println("\n\tKey does not exist in tree...");

    else

    if(T.get_left()==null)

    x=T.get_right();

    else

    if(T.get_right()==null)

    x=T.get_left();

    //next Slide

    36

  • 8/3/2019 Week16 Trees

    37/43

    else //Third case. T has two children. Set x to the

    // inorder successor of T and f to the parent of x.

    {f=T;

    x=T.get_right();

    s=x.get_left();

    while(s!=null)

    {

    f=x;

    x=s;

    s=x.get_left();

    }

    //next Slide

    37

  • 8/3/2019 Week16 Trees

    38/43

    // At this point, x is the inorder successor of T.

    if(f!=T)

    {

    // T is not the parent of x, and x==f.left

    f.set_left(x.get_right());

    // remove x from its current position and replace it

    // with the right child of x

    // x takes the place of T

    x.set_right(T.get_right());

    }

    // set the left child of x so that

    // x takes the place of T

    x.set_left(T.get_left());

    } // end third Case -else

    38

  • 8/3/2019 Week16 Trees

    39/43

    // insert x into the position formerly occupied by T.

    if(P==null)

    root=x;else if(T==P.get_left())

    P.set_left(x);

    else

    P.set_right(x);

    temp=null; //hint to be collected by Garbage Collector

    } End deleteElement

    39

  • 8/3/2019 Week16 Trees

    40/43

    public void PrinBSTNode(BSTNode T)

    {

    System.out.print("\t"+ T.get_value());

    }

    public void printPREorder(BSTNode T)

    {

    if (T !=null)

    {

    PrinBSTNode(T) ;

    printPREorder(T.get_left());

    printPREorder(T.get_right());

    }

    }

    40

  • 8/3/2019 Week16 Trees

    41/43

    public void printINorder(BSTNode T)

    {

    if (T !=null)

    {

    printINorder(T.get_left());

    PrinBSTNode(T) ;

    printINorder(T.get_right());

    }

    }

    public void printPOSTorder(BSTNode T)

    {

    if (T !=null)

    {printPOSTorder(T.get_left());

    printPOSTorder(T.get_right());

    PrinBSTNode(T);

    }

    } 41

  • 8/3/2019 Week16 Trees

    42/43

    public void removeAll(BSTNode T)

    {

    if(T!=null){

    //Traverse the left subtree in postorder

    removeAll(T.get_left());

    //Traverse the right subtree in postorder

    removeAll(T.get_right());

    //Delete the leaf node from the tree

    T=null; //hint to be collected by Garbage Collector

    }

    }

    }//end class

    42

  • 8/3/2019 Week16 Trees

    43/43

    Activity

    1. Write a BSTApp class to create and manipulate a BST

    object (making the different method calls). Create the

    BST by inputting 60, 70, 20, 10, 40, 50, 30 in an initially

    empty BST.

    2. Write a method LeafCount to count the number of leaves

    in a given BST. Test the method in BSTApp.

    3. Write a method SingleChildCount to return the number

    of nodes that have only one child. Test the method inBSTApp.

    43


Recommended