banner



How To Draw A Binary Tree

Binary Copse

Introduction

We extend the concept of linked data structures to structure containing nodes with more than one self-referenced field. A binary tree is made of nodes, where each node contains a "left" reference, a "right" reference, and a data element. The topmost node in the tree is called the root.

Every node (excluding a root) in a tree is connected by a directed edge from exactly 1 other node. This node is called a parent. On the other hand, each node can be connected to arbitrary number of nodes, chosen children. Nodes with no children are called leaves, or external nodes. Nodes which are not leaves are chosen internal nodes. Nodes with the same parent are chosen siblings.

More than tree terminology:

  • The depth of a node is the number of edges from the root to the node.
  • The meridian of a node is the number of edges from the node to the deepest leaf.
  • The pinnacle of a tree is a height of the root.
  • A full binary tree.is a binary tree in which each node has exactly naught or ii children.
  • A complete binary tree is a binary tree, which is completely filled, with the possible exception of the bottom level, which is filled from left to right.

A complete binary tree is very special tree, it provides the best possible ratio betwixt the number of nodes and the height. The height h of a consummate binary tree with N nodes is at most O(log North). Nosotros can hands prove this by counting nodes on each level, starting with the root, assuming that each level has the maximum number of nodes:

            northward = one + two + four + ... + 2h-one          + 2h          = 2h+1          - 1        

Solving this with respect to h, nosotros obtain

            h = O(log due north)        

where the big-O notation hides some superfluous details.

Advantages of trees

Trees are then useful and oft used, because they have some very serious advantages:

  • Trees reverberate structural relationships in the information
  • Trees are used to stand for hierarchies
  • Trees provide an efficient insertion and searching
  • Copse are very flexible data, allowing to motility subtrees effectually with minumum effort

Traversals

A traversal is a procedure that visits all the nodes in the tree. Since a tree is a nonlinear data structure, there is no unique traversal. Nosotros will consider several traversal algorithms with we grouping in the post-obit two kinds

  • depth-first traversal
  • breadth-first traversal

In that location are three different types of depth-commencement traversals, :

  • PreOrder traversal - visit the parent commencement and and then left and right children;
  • InOrder traversal - visit the left child, then the parent and the correct child;
  • PostOrder traversal - visit left child, then the correct child and then the parent;

In that location is but i kind of breadth-first traversal--the level order traversal. This traversal visits nodes by levels from meridian to bottom and from left to correct.

As an example consider the following tree and its 4 traversals:

PreOrder - 8, v, 9, 7, i, 12, two, iv, eleven, iii
InOrder - ix, 5, 1, 7, 2, 12, 8, four, 3, 11
PostOrder - nine, 1, 2, 12, 7, 5, 3, 11, 4, eight
LevelOrder - 8, 5, 4, 9, 7, 11, 1, 12, three, 2

In the next picture we demonstarte the social club of node visitation. Number 1 denote the beginning node in a particular traversal and 7 denote the last node.

These common traversals tin can be represented every bit a single algorithm by assuming that we visit each node three times. An Euler bout is a walk around the binary tree where each edge is treated every bit a wall, which you cannot cantankerous. In this walk each node volition be visited either on the left, or nether the beneath, or on the right. The Euler bout in which we visit nodes on the left produces a preorder traversal. When we visit nodes from the below, nosotros get an inorder traversal. And when nosotros visit nodes on the right, nosotros become a postorder traversal.

Binary Search Copse

Nosotros consider a detail kind of a binary tree called a Binary Search Tree (BST). The bones idea behind this information structure is to accept such a storing repository that provides the efficient style of information sorting, searching and retriving.

A BST is a binary tree where nodes are ordered in the post-obit mode:
  • each node contains one key (also known every bit data)
  • the keys in the left subtree are less and so the central in its parent node, in brusk 50 < P;
  • the keys in the right subtree are greater the cardinal in its parent node, in short P < R;
  • indistinguishable keys are not allowed.

In the following tree all nodes in the left subtree of 10 accept keys < 10 while all nodes in the correct subtree > ten. Because both the left and right subtrees of a BST are again search copse; the above definition is recursively practical to all internal nodes:

Implementation

We implement a binary search tree using a private inner grade BSTNode. In order to support the binary search tree property, we crave that data stored in each node is Comparable:

            public course BST <AnyType extends Comparable<AnyType>>  {     private Node<AnyType> root;       individual class Node<AnyType>     {        individual AnyType data;        private Node<AnyType> left, right;          public Node(AnyType data)        {           left = right = nil;           this.data = data;        }     }     ...    }        

Insertion

The insertion procedure is quite similar to searching. We start at the root and recursively go downwards the tree searching for a location in a BST to insert a new node. If the element to exist inserted is already in the tree, we are done (we do non insert duplicates). The new node volition ever supplant a Cypher reference.

Practise. Given a sequence of numbers:

11, half-dozen, 8, nineteen, four, x, v, 17, 43, 49, 31

Draw a binary search tree by inserting the above numbers from left to right.

Searching

Searching in a BST ever starts at the root. We compare a information stored at the root with the cardinal we are searching for (let u.s.a. call it as toSearch). If the node does not contain the key nosotros keep either to the left or right child depending upon comparison. If the consequence of comparing is negative nosotros go to the left child, otherwise - to the correct child. The recursive structure of a BST yields a recursive algorithm.

Searching in a BST has O(h) worst-example runtime complication, where h is the height of the tree. Since s binary search tree with northward nodes has a minimum of O(log n) levels, it takes at least O(log n) comparisons to detect a particular node. Unfortunately, a binary serch tree can degenerate to a linked list, reducing the search time to O(due north).

Deletion

Deletion is somewhat more tricky than insertion. There are several cases to consider. A node to be deleted (allow us phone call it equally toDelete)

  • is not in a tree;
  • is a foliage;
  • has only one kid;
  • has ii children.

If toDelete is not in the tree, there is nothing to delete. If toDelete node has simply one child the procedure of deletion is identical to deleting a node from a linked listing - nosotros just featherbed that node existence deleted

Deletion of an internal node with two children is less straightforward. If we delete such a node, we split a tree into two subtrees and therefore, some children of the internal node won't be accessible after deletion. In the film beneath we delete 8:

Deletion starategy is the post-obit: replace the node existence deleted with the largest node in the left subtree and and then delete that largest node. By symmetry, the node being deleted tin be swapped with the smallest node is the correct subtree.

See BST.coffee for a complete implementation.

Exercise. Given a sequence of numbers:

eleven, 6, viii, 19, 4, 10, five, 17, 43, 49, 31

Draw a binary search tree by inserting the above numbers from left to correct and then show the 2 copse that can exist the result afterward the removal of xi.

Non-Recursive Traversals

Depth-first traversals tin be easily implemented recursively.A non-recursive implementation is a flake more difficult. In this section nosotros implement a pre-order traversal every bit a tree iterator

            public Iterator<AnyType> iterator()  {    render new PreOrderIterator();  }        

where the PreOrderIterator class is implemented as an inner private form of the BST class

            individual course PreOrderIterator implements Iterator<AnyType>  {    ...  }        

The main difficulty is with next() method, which requires the implicit recursive stack implemented explicitly. We will exist using Coffee's Stack. The algorithm starts with the root and push it on a stack. When a user calls for the next() method, we bank check if the top element has a left child. If information technology has a left kid, we push that child on a stack and return a parent node. If there is no a left child, we check for a correct child. If it has a right child, we push that child on a stack and return a parent node. If in that location is no right child, we motion back up the tree (by popping up elements from a stack) until we find a node with a right child. Hither is the next() implementation

            public AnyType next()  {     Node cur = stk.peek();     if(cur.left != null)     {        stk.push(cur.left);     }     else     {        Node tmp = stk.popular();        while(tmp.right == naught)        {           if (stk.isEmpty()) return cur.information;           tmp = stk.popular();        }        stk.button(tmp.right);     }     render cur.data;  }        

The following example.shows the output and the state of the stack during each call to next(). Note, the algorithm works on any binary trees, non necessarily binary search trees..

Output   i   2   four   half dozen   5   7   8   3
Stack 1 ii
1
four
2
1
six
4
two
1
five
ane
7
5
1
8
1
3

A non-recursive preorder traversal can be eloquently implemented in just three lines of code. If you understand next()'southward implementation higher up, it should exist no problem to grasp this 1:

            public AnyType next()  {     if (stk.isEmpty()) throw new coffee.util.NoSuchElementException();       Node            cur = stk.pop();     if(cur.correct != nil) stk.push(cur.right);     if(cur.left != null) stk.push(cur.left);       return cur.data;  }                  

Note, we push button the right child earlier the left child.

Level Society Traversal

Level order traversal processes the nodes level past level. It first processes the root, and then its children, then its grandchildren, and so on. Different the other traversal methods, a recursive version does not be.

A traversal algorithm is similar to the non-recursive preorder traversal algorithm. The only difference is that a stack is replaced with a FIFO queue.

See BST.java for a consummate implementation.


Victor S.Adamchik, CMU, 2009

Source: https://viterbi-web.usc.edu/~adamchik/15-121/lectures/Trees/trees.html

Posted by: ricetheessale.blogspot.com

0 Response to "How To Draw A Binary Tree"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel