Download as pdf
Download as pdf
You are on page 1of 8
/DULE-5: Binary Trees Binary Trees Trees are hierarchical data structures, unlike arrays, linked lists, stacks, and queues which are linear data structures. A binary tree is a type of tree data structure that has a maximum of two children called the left and the right child. It consists of three parts - data, the reference to left child, and the reference to right child. The uppermost node is called the root and all the other elements are its children. A node without any child is called a leaf node. A binary tree is a non-linear hierarchical data structure consisting of a collection of nodes that stores data forming a hierarchy. It does not store data sequentially as data structures like Arrays, Linked lists, Queues, and Stacks do. Instead, it stores data at multiple levels where each level can store at most 2 children nodes. A tree is made of nodes, and each node contains data, a left pointer, and a right pointer. The uppermost node is referred to as the root, and the bottom-most nodes are referred to as leaf nodes. The nodes that are directly below any node are called children, and those directly above are called the parent. In the following figure, node H is the child of D, and D is the parent of H. Root Levela Level ParentNode —¥(D ) Level ay mtd Node —o(#) LeafNode siblings Level Sub-tee The properties of binary trees include: + Maximum nodes on each level double as we move down the tree. This is because the Number of nodes at any level is equal to 2 raised to the power of n where n is the number of levels starting from 0. +The maximum number of nodes in the last level is equal to one more than the sum of all the nodes in the previous level of a complete binary tree. Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming Let's see how it works. Number of nodes at Oth level = 1 Number of nodes at ist level = 2 = Number of nodes at Oth level +1 Number of nodes at 2nd level = 4 = 1 + 2+ 1 = Number of nodes at Oth level + Number of nodes at 1st level 41 Number of nodes at 3rd level = 8 = 1+2+4+1= Number of nodes at Oth level + Number of nodes at 1st level + Number of nodes at 2nd level + 1 Therefore, the Number of nodes at nth level = Sum of nodes at all n-1 levels + 1 Binary trees have many applications in the real world. Most of the applications use variations of binary trees that are Tries, Binary Search Tree, and B-Trees. They are used for sorting, searching, grouping, and storing data hierarchically. Operations like Insertion, Deletion, and Traversal are applied to them. public class BinaryTree { JI first node private Node root; BinaryTree() { root = null; } 1 Class representing tree nodes static class Node { int value; Node left; Node right; Node(int value) { this. value = value; Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming left = null; right = null; } } public void insert(int i) { root = insert(root, i); } Ilinserting node - recursive method public Node insert(Node node, int value) { if(node == null) return new Node(value); } 1! Move to the left if passed value is I/less than the current node if(value < node.value) { node left = insert(node.left, value); } 1] Move to the right if passed value is greater than the current node else if(value > node. value) { node right = insert(node.right, value); } return node; } I Search node in binary search tree public Node find(int searchedValue) { Node current = root; while(current value != searchedValue) Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming if(searchedValue < current value) J] Move to the left if searched value is less current = current.left; else 1/ Move to the right if searched value is >= current = current.right; if(current == null) { return null; } } return current; } 1 For traversing in order public void inOrder(Node node) { if(node != null) { inOrder(node.left); System.out.print(node.value +" "); inOrder(node right); } } 1] Preorder traversal public void preOrder(Node node) { if(node != null) System.out.print(node.value + ""); preOrder(node.left); preOrder(node.right); } } // Postorder traversal Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming public void postOrder(Node node) { if(node != null) { postOrder(node.left); postOrder(node.right); System.out.print(node.value +" "); } public int calculateSum(Node temp){ int sum, sumLeft, sumRight; sum = sumRight = sumLeft = 0; ICheck whether tree is empty if(root == null) { System.out.printin("Tree is empty"); return 0; } else { l!Calculate the sum of nodes present in left subtree if(temp left != null) sumLeft = calculateSum(temp left); Calculate the sum of nodes present in right subtree if(temp.right != null) sumRight = calculateSum(temp right); {Calculate the sum of all nodes by adding sumLeft, sumRight and root node's data sum = temp.data + sumLeft + sumRight; return sum; Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming IargestElement() will find out the largest node in the binary tree public int largestElement(Node temp) { /iCheck whether tree is empty if(root == null) { System.out.printin("Tree is empty"); return 0; } else { int leftMax, rightMax; Max will store temp's data int max = temp.data; {Nt will find largest element in left subtree if(temp.teft != null} leftMax = largestElement(temp.left); 1]Compare max with leftMax and store greater value into max max = Math.max(max, leftMax); } Nt will find largest element in right subtree if(temp right != null){ rightMax = largestElement(temp right); Compare max with rightMax and store greater value into max max = Math.max(max, rightMax); } return max; } /Mfind the height of tree public int findHeight(Node temp){ J/Check whether tree is empty if(root == null) { System.out printIn("Tree is empty"); Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming return 0; } else { int leftHeight = 0, rightHeight = 0; Calculate the height of left subtree if(temp left != null) leftHeight = findHeight(temp.left); NCalculate the height of right subtree if(temp.right != null) rightHeight = findHeight(temp.right); Compare height of left subtree and right subtree /land store maximum of two in variable max int max = (leftHeight > rightHeight) ? leftHeight : rightHeight; Calculate the total height of tree by adding height of root return (max + 1); } public static void main(Stringl] args) { BinaryTree bst = new BinaryTree(); bst insert(34); bst.insert(56); bst.insert(12); bst.insert(89); bst insert(67); bst.insert(90); System out printin("Inorder traversal of binary tree"); bst.inOrder(bst.root); System out printin(); Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming System out.printin("Preorder traversal of binary tree"); bst preOrder(bst root); System out.printin(); System out printin("Postorder traversal of binary tree"); bst.postOrder(bst.root); System out printin(); ‘System out printin("Sum of all nodes of binary tree: " + bst.calculateSum(bst.root)); } } Output: norder traversal of binary tree 2.34 56 67 89 90 Preorder traversal of binary tree 34 12 56 89 67 90 Postorder traversal of binary ty: hLtps://www. javatpoint.com/binary-tree- java https: //www.scalez.com/topics/binary- tion-in-java/ -implen https: //www. javatpoint .com/binary-tree-java https: //www.edureka.co/blog/java-binary-tree Mrs. Nagarathna Rajendra, Department of TCE, DSCE Java Programming

You might also like