Download as pdf
Download as pdf
You are on page 1of 41
G Signinto GeokstorGecks with Google X. Enguig Jollamae U. nguai@gmal.com . . Continue as Enguig Introduction to Binary Tree - Data § To erate your account, Goole wil share your name, emai adress, and pro picure with GeekstorGeoks. See GeekaforGeeks's privacy policy and terms of sence DSA Array Matrix Strings Hashing Linked list Stack Queue Bing Difficulty Level: Easy» Last Updated : 08 Feb, 2023, Read —Diseuss(60+) Courses Practice Video Atree is a popular data structure that is non-linear in nature. Unlike other data structures like an array, stack, queue, and linked list which are linear in nature, a tree represents a hierarchical structure, The ordering information of a tree is not important. A tree contains nodes and 2 pointers. These two pointers are the left child and the right child of the parent node. Let us understand the terms of tree in detail * Root: The root of a tree is the topmost node of the tree that has no parent node. There is only one root node in every tree. * Parent Node: The node which is a predecessor of anode is called the parent node of that node * Child Node: The node which is the immediate successor of a node is called the child node of that node Wo te cookies to ensure you have the best browsing exparance on our website By sing urs, you seknowogpe that you hve read Got it! fd understood ou Canin Poy 8 Privacy Pale Start Your Coding Journey Now! Login © Subtree: The subtree of a node is the tree considering that particular node as the root node. * Depth: The depth of the node is the distance from the root node to that particular node. * Height: The height of the node is the distance from that node to the deepest node of that subtree. © Height of tree: The Height of the tree is the maximum height of any node, This is the same as the height of the root node. * Level: A level is the number of parent nodes corresponding to a given node of the tree. * Degree of node: The degree of a node is the number of its children © NULL: The number of NULL nodes in a binary tree is (N+1), where N is the number of nodes ina binary tree Wo uso oaks to ensure you hve the best browsing exparonc on our website. By using curs, you arknowlodge that you have ead {nd understood out Conke Palsy & racy Poly Start Your Coding Journey Now! Root key Level 0 Level 1 oat Level 2 Levels Level 4 Iniroduetion to Binary Tree Data Structure a Why to use Tree Data Structure? 1. One reason to use trees might be because you want to store information that naturally forms a hierarchy. For example, the file system on a computer: Wo uso coskes to ensure you hve the best browsing exparonc on our website. By using curs, you arknowlodge that you have ead fd understood or Canin Poy 8 Privacy Pale Start Your Coding Journey Now! syste cs01 est2cst13 2. Trees (with some ordering e.g , BST) provide moderate access/search (quicker than Linked List and slower than arrays) 3. Trees provide moderate insertion/deletion (quicker than Arrays and slower than Unordered Linked Lists), Wo uso oaks to ensure you hve the best browsing exparonc on our website. By using curs, you arknowlodge that you have ead a undorsioe our Cao Play & Privacy Pay Start Your Coding Journey Now! The main applications of tree data structure: 1. Manipulate hierarchical data 2. Make information easy to search (see tree traversal) 3. Manipulate sorted lists of data 4, Asa workflow for compositing digital images for visual effects. 5. Router algorithms 6. Form of multi-stage decision-making (see business chess) 7. Trees can be used to represent the structure of a sentence, and can be used in parsing algorithms to analyze the grammar of a sentence. Wo uso oaks to ensure you hve the best browsing exparonc on our website. By using curs, you arknowlodge thet you have ead {2d understood out Conke Palsy & racy Pocy Start Your Coding Journey Now! 10. Trees are used to represent the syntax of a programming language, and can be used in compiler design to check the syntax of a program and generate machine code Whatis a Binary Tree? Abinary tree is a tree data structure in which each nade can have at most two children, which are referred to as the left child and the right child. The topmost node in a binary tree is called the root, and the bottom-most nodes are called leaves. A binary tree can be visualized as a hierarchical structure with the root at the top and the leaves at the bottom, Binary trees have many applications in computer science, including data storage and retrieval, expression evaluation, network routing, and game Al. They can also be used to implement various algorithms such as searching, sorting, and graph algorithms. Representation of Binary Tree: Each node in the tree contains the following: Wo uso casks to ensure you hve the best browsing exparonc on our website. By using curs, you arknowlodge that you have ead {2nd unersloos out Conke Palsy & racy Polcy Start Your Coding Journey Now! a ae i MR. SANDEEP JAIN Wo use cokes to nour wabste. By using our sto, you a ‘ois Boley & Privacy Poly Start Your Coding Journey Now! their OOP feature, Below is an example of a tree node with integer data, c JJ Structure of each node of the tree struct node ( nt data; struct node Lert; struct node* right; h cH 1/1 Use ary below method to inplenent Nodes of tree 11 Method 1: Using “struct” to make /1 user-cefine data type struct noce ( Ant data; struct node left: struct node* rights 11 Method 2: Using “class” to make Wo uso cooks to ensure you hve the best browsing exparonc on our website. By using ours unos our Cao Play & Privacy Pay you ahnowledpe that you nave rad Start Your Coding Journey Now! Python 4A python class that represents 4 an incividual node in a Binary Tree class Node: def _init_(self, key) gelf.left = None self.right = None self.val = key Java J1 Class containing left and right chile JI of current node and key value class ode ( Ant key; Node left, right; public Node(int iten) £ key = iten; deft = right = mull; Wo uso casks to ensure you hve the best browsing exparonc on our website. By using curs, you arknowlodge that you have ead fd understood ou Canin Poy 8 Privacy Paice Start Your Coding Journey Now! J Class containing left and right chile JI of current node and key value class lode ( Ant keys Node left, rights public Node(dnt item) € key + iten; left » right » mull; Javascript J Class containing left and right chile of current node and key value*/ class Node ‘ constructar(ites) ‘ ‘this key = item; ‘this left = this righ: ula; Wo uso coskes to ensure you hve the best browsing exparonc on our website. By using curs, you arknowodge that you have ead fd understood ou Canin Poy 8 Privacy Pale Start Your Coding Journey Now! ‘* Removing an element. © Searching for an element. * Deletion for an element © Traversing an element. There are four (mainly three) types of traversals in a binary tree which will be discussed ahead. Auxiliary Operations On Binary Tree: * Finding the height of the tree * Find the level of the tree * Finding the size of the entire tree. Applications of Binary Tree: © Incompilers, Expression Trees are used which is an application of binary trees * Huffman coding trees are used in data compression algorithms * Priority Queue is another application of binary tree that is used for searching maximum or minimum in 0(1) time complexity. * Represent hierarchical data * Used in editing software like Microsoft Excel and spreadsheets. * Useful for indexing segmented at the database is useful in storing cache in the systern, © Syntax trees are used for most famous compilers for programming like GCC, and AOCL to perform Wo uso coskes to ensure you hve the best browsing exparonc on our website. By using curs, you arknowodge that you have ead {2nd understood out Conke Palsy & racy Polcy Start Your Coding Journey Now! Used to perform encoding and decoding operations. * Binary trees can be used to organize and retrieve information from large datasets, such asin inverted index and k-d trees. © Binary trees can be used to represent the decision-making process of computer-controlled characters in games, such as in decision trees, * Binary trees can be used to implement searching algorithms, such as in binary search trees which can be used to quickly find an element in a sorted list © Binary trees can be used to implement sorting algorithms, such as in heap sort which uses a binary heap to sort elements efficiently. ary Tree Traversals: Tree Traversal algorithms can be classified broadly into two categories: © Depth-First Search (DFS) Algorithms © Breadth-First Search (BFS) Algorithms ‘Tree Traversal using Depth-First Search (DFS) algorithm can be further classified into three categories: * Preorder Traversal (current-left-right): Visit the current node before visiting any nodes inside the left orright subtrees. Here, the traversal is root - left child - right child. It means that the root node ic travareed firet than ite laft child and finally the rinht child Wo uso casks to ensure you hve the best browsing exparonc on our website. By using curs, you arknowlodge thet you have ead {2nd understood out Conke Palsy & racy Paley Start Your Coding Journey Now! right child, It means that the left child is traversed first then its root node and finaly the right child. + Postorder Traversal (left-right-current): Visit the current nade after visiting all the nodes of the left and right subtrees. Here, the traversalis left child - right child - root. It means that the left child has traversed first then the right child and finaly its root node ‘Tree Traversal using Breadth- toone t Search (BFS) algorithm can be further classit category: © Level Order Traversal: Visit nodes level-by-Level and left-to-right fashion at the same level. Here, the traversal is level-wise. It means that the most left child has traversed first and then the other children of the same level from left to right have traversed. Let us traverse the following tree with all four traversal methods Wo uso oaks to ensure you hve the best browsing exparonc on our website. By using curs, you arknowlodge that you have ead {2d unersoos out Conke Palsy & racy Pocy Start Your Coding Journey Now! Pre-order Traversal of the above tree: 1-2-4-5~: In-order Traversal of the above tree: 4-2-5-1-6-3-7 Post-order Traversal of the above tree: 4-5-2-6-7-3-1 Level-order Traversal of the above tree: 1-2-3-4-5-6-7 Implementation of Binary Tree: Let us create a simple tree with 4 nodes. The created tree would be as follows. Wo use sks to ensure you mve the het bowing experience on or webs, By ing curs, you acknowledge tht you nave 8d nd understood or Canin Poy 8 Privacy Pale Start Your Coding Journey Now! Wo uso coskes to ensure you hve the best browsing exparonc on ou website. By using curs, you arknowlodge that you have ead unos our Cao Pley & Privacy Pay Start Your Coding Journey Now! struct Noce ( int data; Node lefts Node* eights Node(int data) ( this->data = data; this->left = nullpte; this-oright = nullptr; y B class Ginaryiree { public Node* root; BinaryTree() { root = nullptrs y void adcNode(int data) ( Nede* newtlode = new Node (data); 4€ (root root ) else ¢ Noce* focusNode nuliptr) ( newtiodes Wo use cooks to ensure you hve the best browsing exparonc on our website. By using ours 2 undorsios our Cook Pley & Privacy Pay you acknowledge hat you nave rad Start Your Coding Journey Now! Af (data < focusNode->data) { FocusNode = focusNode->lefts AF (FocusNode == nullpte) { parent->left = newNode; return; y ) else ¢ FocusNode = focusNode->rig! AF (focusNode == nullote) ( parent-sright = newNode; return; y ? » x void preordertraversal(Node" focusNode) AF (FocusNode |= nullptr) { std::cout << FocusNode-rdata <<" * preOrderTraversal (FocusNode->left); preOrderTraversal (FocusNode->right) ; y h Ant sain() ( Binarytree trees Wo use cooks to ensure you hve the best browsing exparonc on our website. By using ours a undorsios our Cao Pley & Privacy Pay you acknowledge hat you nave rad Start Your Coding Journey Now! tree. acNode( 30): tree.preordertraversal(tree.root); return 6; > Java class lode ( int data; Node lefts Node rights public Node(int cata) { this.data = data; y ? class sinaryTree ( Node root public void adcNode(int data) { Node newode = new Node(data); Af (root == mull) { root = newNode; Wo use cooks to ensure you hve the best browsing exparonc on our website. By using ours a undorsios our Cao Pley & Privacy Pay you acknowledge hat you nave rad Start Your Coding Journey Now! Af (data < focusNode.data) ( FocusNode = focusnode. lefts Af (FocusNode == mull) { parent.left = newtlodes return; x ) else ( FocusNode = focusNode.right; AF (FocusNode == null) { parent.right = newNode; return; Public void predederTraversat (Node focusNode) { Af (FocusNode != mull) ¢ systes.out.print(FocusNode.data + * preOrderTeaversal (FocusNode. left); preOrderTeaversal(FocusNode. right); y > public class vain ( public static void wain(string{] ares) { Wo use casks to ensure you hve the best browsing exparonc on our website. By using ours a undorsios our Cook Pley & Privacy Pay you acknowledge hat you nave rad Start Your Coding Journey Now! ‘tree.addNode(37); ‘tree. addNode(43); ‘tree. addNode(30) ; ‘tree.preordertraversal((tree.root)s Python3 4 code 41 Definition for a binary tree node class Node: dof _init_(self, data): self.date = data self.left « None self.right = None elas BinaryTree: def _init_(seif): Wo use casks to ensure you hve the best browsing exparonc on our wobsit. By using ours 2 undorsios our Cook Pley & Privacy Pay you acknowledge hat you nave rad Start Your Coding Journey Now! new_node * Node(data) 43 root Js None, assign the new nade to the root Af seif.root 4s None self.root = new_node else: focus node * self root parent = None while Toue paren 4 TF data is less than focus node, assign focus_node to the left chilé Af data < focus node.data focus_node = focus_node. lett # Tf there's no left child, assign the new node to the left child AF focus_node As None: Wo use sks to ensure you hve the het browsing experience on or webs, By ing crs, you acknowledge tht you nave ead fd understood or Canin Poy 8 Privacy Pale Start Your Coding Journey Now! focus_node = Focus_node.right # TF there's no right child, assign the new node to the right child Af focus_node 48. None parent. right = new_node return def prs s_order_traversal(self, focus_node) AF focus_node 4s not None: print(Focus_node.data, ends self.pre_order_traversal (focus_node. left) self.pre_onder_traversal (focus_node. nig 4 Example usage ‘tree = BinaryTree() ‘eree.adé_node(5®) ‘cree.ade_node(25) Wo use casks to ensure you hve the best browsing exparonc on our website. By using ours a undorsios our Cook Pley & Privacy Pay you acknowledge hat you nave rad Start Your Coding Journey Now! sree. adé_node(43) tree. ad_pode(38) ‘tree.pre_order_traversal(tree. root) Javascript IPavascript Code class Node ( constructon(data) ( this.cata = datas this leet = null; this. right = null; > class BinaryTree { constructor() { this.root = auld; ? adeNode(data) { let newode yew Node(data); AF (this.root == mull) { this.root = newode; Wo use casks to ensure you hve the best browsing exparonc on our website. By using ours a undorsios our Cook Pley & Privacy Pay you acknowledge hat you nave rad Start Your Coding Journey Now! Af (data < focusNode.data) { Focuswode = focusnode. lefts AF (FocusNode == mull) { parent.left = newiode; return; > ) else ( FocusNode = focusNode.night; AF (FocusNode == mull) parent.right = newNloge; return; ? » x > prearderTraversal(focusNode) { Af (FocusNode I= ull) { console. 1og(FocusNode. data); this. preorderTraversal (focusNode. left); this. predrderTraversal (focusNode. right); y ? » let tree = new Binarytree(); you acknowledge hat you nave rad Wo use casks to ensure you hve the best browsing exparonc on our wobsit. By using ours fd understood or Canin Poy 8 Privacy Pale Start Your Coding Journey Now! ‘tree.adeNode(3@); ‘tree. preOrdertraversal(tree.root) Output 5@ 25 12 37 30 43 75 Time Complexit} ‘auxil (h), his height of tree jary Space: 0(h), his height of tree. Below is the Implementation of the binary tree: C++ include using namespace ste; elass Node ( public Aint data; Node* left; Node* rights 1/ Val &s the key or the value that 1/ has to be added to the data part Node(int val) Wo use casks to ensure you hve the best browsing exparonc on our website. By using ours a undorsios our Cook Pley & Privacy Pay you acknowledge hat you nave rad Start Your Coding Journey Now! ight = NULL: % int saint) ‘ /*create root*/ Node* root = new Node(1); /* following is the tree after above statement 1 rN NULL NULL ” root -> left = mew Node 2); root -> right = new Node(3); [2 and 3 becone left and right children of 21 1 WN 23 ININ NULL NULL NULL NULL ” root -> left -> left = mew Node(); [7 4 becones left child of 2 a rN 23 Wo use casks to ensure you hve the best browsing exparonc on our wobsit. By using ours 2 undorsios our Cook Pley & Privacy Pay you acknowledge hat you nave rad Start Your Coding Journey Now! c include include struct node ( int data; struct node* ert; struct node* right; h J neaNode() allocates 2 new node with the given data and NULL left and right pointers. */ struct noce* nevNode(int data) 1 Riocate mesory for new node struct node” node = (struct node*)malloc(sizeof(steuct node); 1/ Assign data to this node node-sdata = datas 1/ Initialize left and Wo use cokes to ensure you hve the het browsing experience on or webs, By ing crs, you acknowledge tht you Nave 3d fd understood or Canin Poy 8 Privacy Pale Start Your Coding Journey Now! Ant sain() [terete root*/ struct node root ewode( 1); /* following is the tree after above statenent 1 ry NULL NULL ” root->left = newode(2) 5 root-rright = newtlode(3); J 2 and 3 becone Left and right children of 1 1 1N 23 ININ NULL NULL NULL MULL ” root->left-rleft = newNode(4); 1 4 becones left child of 2 2 rN 23 LAIN 4 NULL NULL NULL Wo use casks to ensure you hve the best browsing exparonc on our website. By using ours fd understood or Canin Poy 8 Privacy Pale you acknowledge hat you nave rad Start Your Coding Journey Now! Java J Class containing left and right chile 11 of current node and key value class Node ( int keys Node left, rights public Node(int iter) £ key = itens eft = right = auld; J] ® Java progran to introduce Binary Tree class BinaryTree ( 11 Root of Binary Tree Node roots 1/ constructors BinaryTree(int key) { root = new Node(key); } Binarytree() { root = nul; ) public static void wain(string[) args) « Wo uso cooks to ensure you hve the best browsing exparonc on our website. By using ours nd undorsios our Caokia Poley & Privacy Pay you acknowledge hat you nave rad Start Your Coding Journey Now! ull null */ ‘tree.root. left = new Node(2); tree,root.right = nem Node(3); J 2 and 3 become eft and right children of 1 1 uN 23 ININ ull pull null null */ ‘tree.root.left.left = new Node(4); J 4 becones Left child of 2 1 1N 23 INTN 4 null nul null IN ult ult ” Python 4 Python program to introduce Binary Tree 1 A class that represents an individual node Wo uso oaks to ensure you hve the best browsing experienc on our website. By using curs, you arknowlodge that you have ead nd understood ou Canin Poy 8 Privacy Pale Start Your Coding Journey Now! self.cight = None self.val = key Af pane == * main Create root root = Node(1) " following 1s the tree after above statenent a iN None None root.left = Node(2) root.right = Node(3) "2 and 3 becone left and right chiléren of 1 a wN 23 ININ None None None None"** root left.left = Node(4) “4 becomes Left child of 2 1 1N 23 ININ 4 None None None yN None None” Wo use casks to ensure you hve th best browsing exparonc on our abst. By using ors unos our Cao Pley & Privacy Pay you ahnowledge that you nave rad Start Your Coding Journey Now! J] 8 Ch program to introduce Binary Tree using systen: J] Class containing left and right chile JI of current node and key value public class Node { public int key: public Node lest, rights public Node(int iten) { key = tens left = right = auld; public class Binaryiree { 11 Root of Binary Tree Node roots 11 Constructors BinaryTree(int key) { root = mew Node(key); } BinaryTree() { root = ull; } 11 briver Coce public static void vain(Stringl) args) € Binarytree tree ~ new BinaryTree(); 11 Create root Wo use casks to ensure you hve th best browsing exparonc on our abst. By using ors unos our Cao Pley & Privacy Pay you ahnowledge that you nave rad Start Your Coding Journey Now! tree.roct.lefe = new Node(2); tree.root.right = new Node(3); J 2 and 3 become eft and right children of 1 1 rN 23 ININ rnulL null null null */ tree.root.left.left = mew Node(4); [7 4 becones Left child of 2 1 WN 23 ININ 4 null null ult iN ull nut? ” JJ This code 4s contributed by PrineiRaji992 Javascript Wo uso oaks to ensure you hve the best browsing exparonc on our website. By using curs, you arknowlodge thet you have ead fd understood ou Canin Poy 8 Privacy Pale Start Your Coding Journey Now! thts. key = vals this.left = nul; this.right = null; + + 11 & Javascript program to introduce Binary Tree 1] Root of Binary Tree ul; Itereate root*/ oot = new Node(1); /* following is the tree after above statenent a WN null null */ root.left = new Node(2); root.right = mew Node(3); /* 2 and 3 become left and right children of 1 \ 3 Wo uso cooks to ensure you hve the best browsing exparonc on our wobsit. By using ours 2 undorsioe our Cook Pley & Privacy Pay you ahnowledge that you nave rad Start Your Coding Journey Now! a WN 23 ININ 4 null null null WN pull null ” Summary: Tree is a hierarchical data structure. Main uses of trees include maintaining hierarchical ete operations, Binary trees are special cases of tree data, providing moderate access and insert/ has at most two children e every n Binary Trees (Introduction) | GeeksforGeeks Wo use cokes to ensure you mve the het bowing exarone on or webs, By ing crs, you acknowledge tht you nave ead unos our Cao Pley &Pavacy Pay Start Your Coding Journey Now! ‘Typesof Binary Tree ase write comments if you find anything incorrect, or you want information about the opic discussed above Solve Problems Solve DSA problems on GfG Practice. waa LEARY: ARRAYS, DP TIE, HASH — 26 commen novancen torts EB wsiweco SS. Like 1.31k Next Properties of Binary Tree Wo uso oaks to ensure you hve the best browsing exparonc on our website. By using curs, you arknowlodge that you have ead 2 undorsioe our Cook Pley & Privacy Pay Start Your Coding Journey Now! 1. Introduction to Divide and Conquer Algorithm - Data Structure and Algorithm Tutorials 2. Introduction to Tree Data Structure and Algorithm Tutorials 3. Introduction to Recursion - Data Structure and Algorithm Tutoriale 4. Introduction to Stack - Data Structure and Algorithm Tutoriale 8. Introduction to Queue - Data Structure and Algorithm Tutorials 6. Introduction to Arrays - Data Structure and Algorithm Tutorials 7. Introduction to Linked List ~ Data Structure and Algorithm Tutorials 8. Introduction te Hashing - Date Structure and Algorithm Tutorials 9. Introduction to Segment Trees - Data Structure and Algorithm Tutorials 10. Introduction to Heap - Data Structure and Algorithm Tutorials Wo uso coskes to ensure you hve the best browsing exparonc on our website. By using curs, you arknowlodge that you have ead unos our Cao Pley & Privacy Pay Start Your Coding Journey Now! Vote for difficulty Current difficulty: Easy. Improved By: nsp$2, princiraji982, marikante2901, Twink! Bajaj, anandpatel98260, umadevis6is, putitinwafi, shreyasnaphad, hardikkoriintern, preetilobra8448, chiragmundra2002, harendrakumari23, susebhanakhull itsadityash, laxmishindest82, okshaytripathil94i0, NikunjDaskosat, satwiksuman, vforviksvyS ArticleTags: DSA, Tree Practice Tags: Tree Improve Article Report Issue OG Wo uso coskes to ensure you hve the best browsing exparonc on our website. By using curs, you arknowlodge that you have ead fd understood or Canin Poy 8 Privacy Paice Start Your Coding Journey Now! Company About Us Careers In Media Contact Us Privacy Policy Copyright Policy Advertise with us News Top News Technology Work & Career Business Finance LUfestyle Knowledge Learn sa Algorithms Data Structures SDE Cheat Sheet Machine learning cS Subjects Video Tutoriale Courses Languages Python Jove cpp Golang c# sat ketlin Wo use sks to ensure you hve the het housing experience on or webs, By ing curs, you acknowledge tht you Nave ead nd understood ou Canin Poy 8 Privacy Pale Start Your Coding Journey Now! HTM Pick Topies fo Write Jovaseript Write Interview Experience Bootstrap Internships Reacts Video internship Nodes ageskstorgesks Some rights reserved Please Login To Continue x @ signin Osign Up Username or emai Password Remember me Forgot Password Sign in E-mail Password InsttstanfOrganzaton Sign Up Pesto Wo uso oaks to ensure you hve the best browsing exparonc on our website. By using curs, you arknowodge that you have ead nd understood ou Canin Poy 8 Privacy Pale Start Your Coding Journey Now! ‘coating this account. you agro fo ou Privacy Policy & Cook Pl less eneryouremal'adcass or vsetfenda. te UsernamelEmall Back Lenin Reset Password Wo use sks to ensure you mve the het browsing experience on or webs, By ing crs, you acknowledge tht you nave ead 2 undorsioe our Cook Pley & Privacy Pay

You might also like