Binary Tree

Recursion

When a function calls itself

Examples of Recursion

public static int getFib(int n) {
    if (n < 2)
        return n;
    return getFib(n - 1) + getFib(n - 2);
}

Fibonacci numbers

Examples of Recursion

public static boolean isOdd(int n) {
	if(n == 1) {
		return true;
	}
	return !isOdd(n-1);
}

Is `n` an odd number

Examples of Recursion

Are the brackets correct?

Definition on Correct brackets:

<Correct brackets> are:

  1. ()

  2. (<Correct brackets>)

  3. <Correct brackets><Correct brackets>

Examples of Recursion

public static boolean brackets(String b) {
    if (b.length() == 2 && b.charAt(0) == '('
        && b.charAt(1) == ')')
	    return true;
    if (b.charAt(0) == '(' 
        && b.charAt(b.length()-1) == ')'
        && brackets(b.substring(1, b.length() - 1)))
	    return true;
    for (int i = 2; i < b.length(); i+=2) {
        if( brackets(b.substring(0,i)) 
            && brackets(b.substring(i, b.length()))){
	    return true;
	}
    }
    return false;
}

And now, some questions:

How fast can we access elements in an array?

  • Search                 n operations

  • Insert                   1 operation

  • Remove              n operations

How fast can we access elements in a linked list?

  • Search                 n operations

  • Insert                   1 operation

  • Remove              n operations

How fast can we access elements in a sorted array?

  • Search                 log(n) operations

  • Insert                   n operations

  • Remove              n operations

( Note: We can use Binary search )

How fast can we access elements in a Binary search tree?

  • Search                 log(n) operations

  • Insert                   log(n) operations

  • Remove              log(n) operations

What is a binary search tree?

Binary Tree

By Hack Bulgaria

Binary Tree

  • 1,892