Tirgul no' 12 - PowerPoint PPT Presentation

About This Presentation
Title:

Tirgul no' 12

Description:

The root of a tree is the only node which doesn't have a parent node. ... descendants of. RuntimeException. checked. unchecked. Checked versus Unchecked Exceptions ... – PowerPoint PPT presentation

Number of Views:40
Avg rating:3.0/5.0
Slides: 18
Provided by: csHu
Category:
Tags: tirgul | unchecked

less

Transcript and Presenter's Notes

Title: Tirgul no' 12


1
Tirgul no. 12
  • Topics covered
  • Binary Search Trees
  • Exception Handling in java

2
Binary Search Tree
  • Definitions
  • The root of a tree is the only node which
    doesnt have a parent node.
  • A leaf is a node which doesnt have any
    descendant nodes.
  • A binary tree is a tree whose nodes have at
    most two immediate descendant
  • nodes.
  • A binary search tree is
  • 1. A binary tree.
  • 2. All the nodes which are descendents
    of the right son of a specific node
  • including the right son itself have
    values greater than the value in
  • the current node.
  • 3. All the nodes which are descendants
    of the left son of a specific node
  • including the left son itself have
    values less than the value in the node.

In the example b,c,d,e,f gt a b gt d,e,f
a
root
b
d
c
e
f
leaves
3
Binary Search Tree Methods
  • The binary search tree supports the following
    basic operations
  • InorderTreeWalk Printing the data inorder
    (sorted)
  • Search search for the given data in the tree.
  • Insert insert new data into the sorted tree.
  • Delete delete new data from the tree

4
Binary Tree Node
public class TreeNode protected Comparable
data protected Node left,right,parent
public Node(Comparable data) this.data
data left right parentnull
public void setRight(Node node) right
node node.parent this public void
setLeft(Node node) left node
node.parent this
public Node getRight() return right
public Node getLeft() return left
public Node getParent() return(parent)
public Comparable getData() return
data
5
Class BinarySearchTree
  • public class BinarySearchTree
  • protected Node root
  • //some constructors
  • //methods (on next slides)

6
InorderTreeWalk
  • public void inorderTreeWalk()
  • inorder(root)
  • //recursively traverse the tree
  • private void inorder(Node node)
  • if(node!null) //stopping condition
  • inorder(node.getLeft())
  • System.out.println(node.getData())
  • inorder(node.getRight())

7
Search
  • public Node search(Comparable data)
  • return(treeSearch(root,data))
  • //recursively search the tree
  • public Node treeSearch(Node node, Comparable
    data)
  • if( (node null)
  • (node.getData().compareTo(data)
    0)
  • return(node)
  • if(node.getData().compareTo(data) gt 0)
  • return(treeSearch(node.getLeft(),data)
  • else
  • return(treeSearch(node.getRight(),data)

8
Insert
  • public void insert(Comparable data)
  • Node currParent null
  • Node node root
  • while(node ! null)
  • currParent node
  • if(node.getData().compareTo(data) gt 0 )
  • node node.getLeft()
  • else
  • node node.getRight()
  • Node newNode new Node(data)
  • if( currParent null) //tree is empty!
  • root newNode
  • else if( currParent.getData().compareTo(data) gt
    data)
  • currParent.setLeft(newNode)
  • else
  • currParent.setRight(newNode)

9
Deletion
  • if(temp ! null)
  • temp.parent helper.parent
  • //check if successor is root node
  • if(helper.getParent() null)
  • root temp
  • else if (helper helper.getParent().getLeft() )
  • helper.getParent().setLeft(temp)
  • else
  • helper.getParent().setRight(temp)
  • if( helper ! delNode)
  • //copy all fields of y
  • delNode.setData(helper.setData())
  • return(helper)
  • //end of method
  • public Node delete(Comparable data)
  • Node delNode search(data)
  • if(delNode null)
  • return
  • Node helpernull
  • Node temp null
  • //decide which node to splice
  • if( (delNode.getLeft() null)
  • (delNode.getRight() null) )
  • helper delNode
  • else
  • helper TreeSuccessor(delNode)
  • //check for sons of splice node
  • if(helper.getLeft() ! null)
  • temp helper.getLeft()
  • else
  • temp helper.getRight()

10
Exceptions
  • The way we deal with errors, exceptional/abnormal
    situations in
  • the java programming language is by throwing
    exceptions.
  • Exceptions are instances of classes which are
    descendants of the
  • class Exception.

The Throwable family
Throwable
descendants of Throwable
Exception
RunTimeException
Generally work with this subtree
11
Exceptions details
  • Many types of exceptions in java for examples
    look at java.lang api.
  • We can create our own types of exceptions by
    extending existing types.
  • Any Exception which is not a descendant of
    RuntimeException must be caught by a method or
    the method must be declared to throw the
    exception (more on this in a couple more slides).

12
Why do we use exceptions?
  • Make the code more readable - it separates the
    algorithm from error handling.
  • There are cases where returning a value to
    indicate errors is impossible or not reasonable -
    constructors and void methods.
  • Easier to indicate different types of errors.
  • Easy to propagate errors up the calling stack.

13
How to use Exceptions
try // guarded code. // exceptions A,B and C
might be thrown here. catch (A a) // what to
do if A is thrown. catch (B b) // handle B
here. catch (C c) // and here we have a
chance to handle C. finally // Thing that
must happens after the rest of the code, // if
an exception is thrown or not.
14
Example Reading a file
We want to read a file into memory. readFile
() open the file determine its size
allocate that much memory read the file
into memory close the file
15
Reading file - without exceptions
int readFile() openFile if (file not opened)
// handle the error return -1 get the
file length if (cannot get the length) //
handle this error close file return
-2 allocate memory for the data if (not
enough memory) // another error to
handle. close file return -3
read data if (read failed) // handle
again. close file return -4 close file
// after read. reutrn 0 // success.
16
Reading file - with exceptions
void readFile() try open file get file
size allocate memory read file catch
(FileNotOpened e1) // handle this. catch
(CannotGetFileLength e2) // another handeling
code. catch (MemoryAllocationFailed e3) //
yet another error. catch (ReadFailed e4)
// the last handle here. finally
if(file is open) close file

This is the algorithm

Error handling
code that happens in any case

17
Recovering from errors
public class Example public static void
main(String args) SimpleInput sin new
SimpleInput(System.in) int num boolean
ok false while(!ok) try
System.out.print("Enter an integer ")
num sin.readlnInt() ok true
catch(NumberFormatException nfe)
System.err.println("Read (" nfe.getMessage()
") not an integer.")
catch(IOException ioe)
System.err.println("Fatal IO error.\n" ioe
"Exiting program.")
System.exit(1)
18
Throwing exception from the constructor
public class NimBoard private int heaps
public NimBoard(int size) throws
IllegalSizeException if(sizelt1) throw
new IllegalSizeException(size) heaps new
intsize // other methods of NimBoard
19
Defining a new exception type
public class IllegalSizeException extends
IllegalArgumentException public
IllegalSizeException() super()
public IllegalSizeException(String message)
super(message) public
IllegalSizeException(int size)
super("Illegal nim board size ( " size
")")
20
Checked versus Unchecked Exceptions
Throwable
Exception
descendants of Throwable
RunTimeException
any class other than RunTimeException
descendants of RuntimeException
Write a Comment
User Comments (0)
About PowerShow.com