Sunday, 3 April 2016

Binary Tree & Binary Search Tree 

 

1. Binary Tree (BT) is a special type of tree data structure because any parent node has 2 child nodes at most. Below is the implementation of BT in Python.

class BinaryNode():   
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left, self.right = left, right

Unlike the parent node in a  tree that uses a list to contain the child nodes, the parent node in a BT directly connects to child nodes, which is more like a node in the linked list. This structure result in different orders of walking though the nodes as deep as possible: in-order, pre-order and post-order.

 A simple BT is like:
                   1
           2              3      
       4      5       6      7

In-order visit is like:  (4-->2-->5)--->1--->(6-->3-->7)
Pre-order visit is like: 1---> (2-->4-->5)--->(3-->6-->7)
Post-order visit is like: (4-->5-->2)--->(6-->7-->3)--->1

We may image that the ordering is applied firstly to each simple sub-trees (just parent and child nodes), and then to the larger sub-trees, and finally to the entire tree.

2. The recursive Depth-First-Search (BFS) for a BT is almost same as that for a tree except the data structure of the child nodes. Below is a recursive DFS function used to print each root-to-leaf path of a BT. The base case is if the leaf node (bn.left is None and bn.right is None) is reached. The core of the function is to avoid the list mutation when the recursion moves downward to left and/right right child nodes.

def print_path_recurr(bn, path = []):
    if not bn.left and not bn.right:
        path += str(bn.data)
        print('---> '.join(path))
    else:
        path += [str(bn.data)]
        if bn.left:
            print_path_recurr(bn.left, path.copy())
        if bn.right:
            print_path_recurr(bn.right, path.copy())

3. As mentioned before, the recursion is not a good choice for the Breadth-First-Search (BFS) of a BT. So the queue is regularly used to code the iterative BFS function, which is discussed in details in the previous post "Stack and Queue: More Application".

4. Binary Search Tree (BST) is a branch of BT if we use the condition: value of left child node < value of parent node < value of right node to set up a sorted BT. Accordingly the implementation of a BST is identical to that of a BT. A simple BST is like:

                   5
         2                  7
   1        3          6      8

So the oder of the nodes in the BST is straightforward:  (1  <  2  <  3)  <  5  <  (6  <  7  <  8).

The DFS of a BT requires to search both left and right node. But the DFS of a BST just need to search either left or right child node (not both). For example,  as to the BST above, the path of searching 8 is:

 5--->7--->8.

But, if the tree was a BT, the paths include:

5--->2--->1,  5--->2--->3,
5--->7--->6,  5--->7--->8.

Below is a recursive DFS function used to check if an item is contained in the BST.  Note the function relies on the implementation of BT. The base case is if a BT node is existed or not (not if a leaf node is reached because the function check all nodes including leaf nodes). The core of the function is to always choose between left and right child node before the function moves downward.

def bst_contain(bn, item):
    if not bn:
        return False
    elif item == bn.data:
        return True
    elif item < bn.data:
        return bst_contain(bn.left, item)
    else:
        return bst_contain(bn.right, item)

Below is another recursive function used to check if a BT is BST. Recall that the left child nodes is less than the parent node and the right child node is larger than that. So the core of the function is to bring the parent nodes' values downward when the function is visiting the lower nodes. 

def is_bst(bn, mini=-10000, maxm=10000):           
    if not bn:
        return True       
    elif bn.data < mini or bn.data > maxm:
        return False               
    else:        
        return is_bst(bn.left, mini, bn.data) and is_bst(bn.right, bn.data, maxm)



End of this post

No comments:

Post a Comment