Drawing a Tech Tree at Runtime

Introduction

Hi friends, today, I am going to discuss the small data structure topic of Trees. Before we go deep into this concept, I want to explain:

  1. What is a Tree?
  2. Why do we need a Tree?
  3. Tree Terminologies

What is a Tree?

  • A Tree is used to represent data in a hierarchical format
  • Every node in a tree has 2 components (Data and References)
  • The top node of the tree is called the Root node and the 2 products under it are called "Left Subtree" and "Right Subtree".

Picture representation of a tree:

Why do we need a Tree?

  • When we compare a Tree with other data structures, like arrays or a LinkedList, we need not have to mention the size of the tree, hence it is space efficient.
  • A linked list has big O(n) operation for insertion, deletion, and searching, whereas, with Trees, we do not have such a problem.

Tree Terminologies

  • "A"  represents the Root node (which do not have a parent)
  • "Edge" is a link between Parent and a Chid (Ex: B to D)
  • "Leaf" node with no children (Ex: D, E, F, G)
  • "Sibling" children of the same parent (Ex: D and E are Siblings, they both have Same parent B)
  • "Ancestor" parent, grandparent for a given node (Ex: D's ancestor is B and A)
  • "Depth of a node" length of the path from the root to that node (Ex: D's depth is 2)
  •  "Height of a Node" height from a particular node to the deepest node (leaf node) (Ex: height of B is 1 (B to D))

Binary Tree

A tree is said to be a Binary tree if each node has zero, one or two children.

Types of Binary Trees:

  • Strict Binary Tree
  • Full Binary Tree
  • Complete Binary Tree

Strict BinaryTree

Each node has either two children or none.

Full Binary Tree

Each Non-leaf node has two children and all the leaf nodes are at the same level.

Complete Binary Tree

If all the levels are completely filled, except the last level and the last level has all the keys as left as possible

Tree Representation can be implemented in two ways.

  1. Using a Linkedlist
  2. Using an Array

In this article, I am going to implement a Linked list.

First, let's look at an example of how tree data is stored in a linked list. Below is the pictorial representation:

In the above image, the left image represents a Binary Tree and the Right Image represents a LinkedList arrangement of numbers. Inside the address of the root, the next node value is stored. When there is no leaf/ child node for a node then the memory address of that node will be represented as "null".

Create a blank Binary Tree:

  1. public  Class BinaryTreeByLinkedList{
  2.    BinaryNode root;
  3. public  BinaryTreeByLinkedList(){
  4. this .root = null ;
  5.   }
  6. }

Time Complexity: O(1)

Space Complexity: O(1)

Depth - first Search of a Binary tree has 3 types

Pre-Order Traversal

Consider the above Binary tree as an example. In Pre-order traversal we need to traverse (Root, Left, Right). For the above example, the output should be 20,100,50,222,15,3,200,35

Algorithm for Pre-Order Traversal

         Preorder(BinaryNode root)

            if(root is null) return errorMessage

            else

            print root

            Preorder(root.left)

            Preorder(root.right)

     Time Complexity: O(n)

     Space Complexity: O(n)

Code for Pre Order Traversal:

  1. void  preOrder(BinaryNode node) {
  2. if  (node == null )
  3. return ;
  4.                             Console.WriteLine(node.getValue() +" " );
  5.                             preOrder(node.getLeft());
  6.                             preOrder(node.getRight());
  7.                          }

In-Order Traversal

Consider the above Binary tree as an example. With in-order traversal, we need to traverse (Left, Root, Right). In the above example, the output should be 222,50,100,15,20,200,3,35

Algorithm for In-Order Traversal

          InOrderTraversal(BinaryNode root)

           if(root equals null) return error message

           else

              InOrderTraversal(root.left)

              print root

              InOrderTraversal(root.right)

  1. Code for  In-Order Traversal
  2. void  inOrder(BinaryNode node) {
  3. if  (node == null ) {
  4. return ;
  5.               }
  6.               inOrder(node.getLeft());
  7.               Console.WriteLine(node.getValue() +" " );
  8.               inOrder(node.getRight());
  9.               }

Time Complexity: O(n)

Post-Order Traversal

Consider the above Binary tree as an example. For post-order traversal, we need to traverse (Left, Right, Root). For the above example, the output should be: 222, 50,100,15,20,200,3,35

Algorithm for Post-Order traversal

      PostOrderTraversal(BinaryNode root)

      if(root equals null) return errorMessage

      else

        PostOrderTraversal(root.left)

        PostOrderTraversal(root.right)

        print root

Time Complexity: O(n)

Space Complexity: O(n)

  1. void  postOrder(BinaryNode node) {
  2. if  (node == null )
  3. return ;
  4.             postOrder(node.getLeft());
  5.             postOrder(node.getRight());
  6.             Console.WriteLine(node.getValue() +" " );
  7.             }

Level Order Traversal (Breadth-First Search of Binary Tree)

Consider above Binary Tree as an example. The output for above example is: 20,100,3,50,15,250,35,222

Algorithm for Level-Order traversal

     LevelOrderTraversal(BinaryNode root)

     CreateQueue(q)

     enqueue(root)

     while(q is notEmpty)

         print root

         enqueue()

        dequeue() and Print

TimeComplexity: O(n)

SpaceComplexity: O(n)

  1. Code for  Level-Order Traversal
  2. void  levelOrder() {
  3.                  Queue<BinaryNode> queue =new  LinkedList<BinaryNode>();
  4.                  queue.add(root);
  5. while  (!queue.isEmpty()) {
  6.                              BinaryNode presentNode = queue.remove();
  7.                              System.out .print(presentNode.getValue() + " " );
  8. if  (presentNode.getLeft() != null ) {
  9.                                       queue.add(presentNode.getLeft());
  10.                                    }
  11. if  (presentNode.getRight() != null ){
  12.                                       queue.add(presentNode.getRight());
  13.                                    }
  14.                           }
  15.                   }

Search a Value in Binary Tree

In order to search for a value in a Binary tree, it is always good to use a Queue rather than stack. (i.e Using level-Order traversal is the best way to search a value)

If we want to search the value "15" from above tree, we can use BFS. At Level3, we have the value 15.

  1. void  search( int  value) {
  2.                 Queue<BinaryNode> queue =new  LinkedList<BinaryNode>();
  3.                 queue.add(root);
  4. while  (!queue.isEmpty()) {
  5.                 BinaryNode presentNode = queue.remove();
  6. if  (presentNode.getValue() == value) {
  7.                          Console.WriteLine("Value-" +value+ " is found in Tree !" );
  8. return ;
  9.                        }else  {
  10. if  (presentNode.getLeft()!= null )
  11.                                   queue.add(presentNode.getLeft());
  12. if  (presentNode.getRight()!= null )
  13.                                   queue.add(presentNode.getRight());
  14.                               }
  15.                       }
  16.                 Console.WriteLine("Value-" +value+ " is not found in Tree !" );
  17.              }

Insertion of a Node in BinaryTree

Below are two conditions we need to consider while inserting a new value in BinaryTree:

  1. When the Root is blank
  2. Inserting a new node at the first vacant child
  1. void  insert( int  value) {
  2.                      BinaryNode node =new  BinaryNode();
  3.                      node.setValue(value);
  4. if  (root == null ) {
  5.                                  root = node;
  6.                                  Console.WriteLine("Successfully inserted new node at Root !" );
  7. return ;
  8.                      }
  9.                      Queue<BinaryNode> queue =new  LinkedList<BinaryNode>();
  10.                      queue.add(root);
  11. while  (!queue.isEmpty()) {
  12.                                  BinaryNode presentNode = queue.remove();
  13. if  (presentNode.getLeft() == null ) {
  14.                                              presentNode.setLeft(node);
  15.                                              Console.WriteLine("Successfully inserted new node !" );
  16. break ;
  17.                                  }else if  (presentNode.getRight() == null ) {
  18.                                  presentNode.setRight(node);
  19.                                  Console.WriteLine("Successfully inserted new node !" );
  20. break ;
  21.                                  }else  {
  22.                                     queue.add(presentNode.getLeft());
  23.                                     queue.add(presentNode.getRight());
  24.                                    }
  25.                               }
  26.                           }

Delete Node in a Binary Tree

Two rules before deleting a node from a Binary Tree:

  • When the value does not exist in a BinaryTree
  • When the value needs to be deleted exists in the tree

If a value to be deleted exists in the tree, then we need to delete the deepest node from the BinaryTree. For example, if the node to be deleted is the root node, then find the deepest node in the binary tree and replace it with the root node, then delete the deepest node.

Code to delete the deepest node in the Binary Tree:

  1. public void  DeleteDeepestNode() {
  2.                     Queue<BinaryNode> queue =new  LinkedList<BinaryNode>();
  3.                     queue.add(root);
  4.                     BinaryNode previousNode, presentNode =null ;
  5. while  (!queue.isEmpty()) {
  6.                                          previousNode = presentNode;
  7.                                          presentNode = queue.remove();
  8. if  (presentNode.getLeft() == null ) {
  9.                                                         previousNode.setRight(null );
  10. return ;
  11.                                             }else if  ((presentNode.getRight() == null )) {
  12.                                                           presentNode.setLeft(null );
  13. return ;
  14.                                             }
  15.                                             queue.add(presentNode.getLeft());
  16.                                              queue.add(presentNode.getRight());
  17.                                 }
  18.                              }
  19. public  BinaryNode getDeepestNode() {
  20.                                 Queue<BinaryNode> queue =new  LinkedList<BinaryNode>();
  21.                                 queue.add(root);
  22.                                 BinaryNode presentNode =null ;
  23. while  (!queue.isEmpty()) {
  24.                                                   presentNode = queue.remove();
  25. if  (presentNode.getLeft() != null )
  26.                                                         queue.add(presentNode.getLeft());
  27. if  (presentNode.getRight() != null )
  28.                                                          queue.add(presentNode.getRight());
  29.                                                   }
  30. return  presentNode;
  31.                           }
  32.            Code to Delete a value from BinaryTree
  33. void  deleteNodeOfBinaryTree( int  value) {
  34.                                   Queue<BinaryNode> queue =new  LinkedList<BinaryNode>();
  35.                                    queue.add(root);
  36. while  (!queue.isEmpty()) {
  37.                                             BinaryNode presentNode = queue.remove();
  38. if  (presentNode.getValue() == value) {
  39.                                                            presentNode.setValue(getDeepestNode().getValue());
  40.                                                            DeleteDeepestNode();
  41.                                                            Console.WriteLine("Deleted the node !!" );
  42. return ;
  43.                                                }else  {
  44. if  (presentNode.getLeft() != null )
  45.                                                            queue.add(presentNode.getLeft());
  46. if  (presentNode.getRight() != null )
  47.                                                                      queue.add(presentNode.getRight());
  48.                                          }
  49.                              }
  50.                                Console.WriteLine("Did not find the node!!" );
  51.                           }

Delete Entire BinaryTree

  1. void  deleteTree() {
  2.     root =null ;
  3.     Console.WriteLine("Binary Tree has been deleted successfully" );
  4. }

Conclusion

In this article, I have explained the types of trees, depth-first search, and breadth-first search. This article is completely for beginners. If there are any updates or anything needs attention, please feel free to comment below.

bardonwearprapart.blogspot.com

Source: https://www.c-sharpcorner.com/article/tree-data-structure/

0 Response to "Drawing a Tech Tree at Runtime"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel