Trees PDF
Trees PDF
1
Contents
17 Binary Tree to Binary Search Tree Conversion using STL set 144
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
26 Change a Binary Tree so that every node stores sum of all nodes in left
subtree 195
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
29 Check given array of size n can represent BST of n levels or not 210
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
2
Contents
37 Check if a given Binary Tree is height balanced like a Red-Black Tree 259
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
45 Check if removing an edge can divide a Binary Tree in two halves 304
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
46 Check if the given array can represent Level Order Traversal of Binary
Search Tree 313
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
3
Contents
52 Check if two trees are mirror of each other using level order traversal 341
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
4
Contents
74 Construct Complete Binary Tree from its Linked List Representation 476
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
75 Construct Full Binary Tree from given preorder and postorder traversals486
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
76 Construct Full Binary Tree using its Preorder traversal and Preorder
traversal of its mirror tree 493
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
5
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
81 Construct a complete binary tree from given array in level order fashion534
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
83 Construct a tree from Inorder and Level order traversals | Set 1 545
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
84 Construct a tree from Inorder and Level order traversals | Set 2 554
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
85 Construct the full k-ary tree from its preorder traversal 558
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
89 Convert a Binary Tree into Doubly Linked List in spiral fashion 576
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
91 Convert a Binary Tree such that every node stores the sum of all nodes
in its right subtree 593
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
92 Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue) 597
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603
6
Contents
99 Convert a given Binary tree to a tree that holds Logical AND property 646
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
103 Convert an arbitrary Binary Tree to a tree that holds Children Sum
Property 665
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672
108 Count elements which divide all numbers in range L-R 688
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
109 Count full nodes in a Binary tree (Iterative and Recursive) 695
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
110 Count half nodes in a Binary tree (Iterative and Recursive) 704
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711
111 Count pairs in a binary tree whose sum is equal to a given value x 712
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719
7
Contents
113 Count the number of nodes at given level in a tree using BFS. 727
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731
116 Create loops of even and odd values in a binary tree 744
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 747
119 DFS for a n-ary tree (acyclic graph) represented as adjacency list 758
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 761
122 Deepest left leaf node in a binary tree | iterative approach 772
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 774
123 Deepest right leaf node in a binary tree | Iterative approach 775
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 777
8
Contents
130 Depth of the deepest odd level node in Binary Tree 801
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804
138 Difference between sums of odd level and even level nodes of a Binary
Tree 845
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 851
9
Contents
158 Find all possible binary trees with given Inorder Traversal 967
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 974
159 Find depth of the deepest odd level leaf node 975
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 982
161 Find distance from root to given node in a binary tree 999
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1001
162 Find first non matching leaves in two binary trees 1002
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1005
163 Find height of a special binary tree whose leaf nodes are connected 1006
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1008
10
Contents
164 Find if given vertical level of binary tree is sorted or not 1009
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1013
165 Find if there is a pair in root to a leaf path with sum equals to root’s
data 1014
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1017
166 Find largest subtree having identical left and right subtrees 1018
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1021
179 Find right sibling of a binary tree with parent pointers 1079
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1084
180 Find root of the tree where children id sum for every node is given 1085
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1086
11
Contents
181 Find sum of all left leaves in a given Binary Tree 1087
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1098
182 Find sum of all nodes of the given perfect binary tree 1099
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1106
183 Find sum of all right leaves in a given Binary Tree 1107
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1110
187 Find the largest BST subtree in a given Binary Tree | Set 1 1127
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1135
188 Find the maximum node at a given level in a binary tree 1136
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1140
189 Find the maximum path sum between two leaves of a binary tree 1141
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1148
190 Find the maximum sum leaf to root path in a Binary Tree 1149
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1149
191 Find the node with minimum value in a Binary Search Tree 1150
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1155
196 General Tree (Each node can have arbitrary number of children) Level
Order Traversal 1188
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1190
12
Contents
200 Given a binary tree, how do you remove all the half nodes? 1203
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1209
202 Given a binary tree, print out all of its root-to-leaf paths one per line.1217
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1223
203 Given a n-ary tree, count number of nodes which have more number
of children than parents 1224
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1226
204 Given level order traversal of a Binary Tree, check if the Tree is a
Min-Heap 1227
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1230
207 Height of a complete binary tree (or Heap) with N nodes 1237
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1240
209 Height of binary tree considering even level leaves only 1247
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1250
212 If you are given two traversal sequences, can you construct the binary
tree? 1268
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1269
13
Contents
215 Inorder Non-threaded Binary Tree Traversal without Recursion or Stack 1284
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1291
218 Inorder Tree Traversal without recursion and without stack! 1308
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1314
219 Inorder predecessor and successor for a given key in BST 1315
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1322
227 Iterative Segment Tree (Range Maximum Query with Node Update) 1368
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1371
14
Contents
231 Iterative method to check if two trees are mirror of each other 1383
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1386
237 K’th Largest Element in BST when modification to BST is not allowed 1404
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1410
238 LCA for general or n-ary trees (Sparse Matrix DP approach <
O(nlogn), O(logn)>) 1411
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1417
244 Largest value in each level of Binary Tree | Set-2 (Iterative Approach)1443
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1446
245 Leaf nodes from Preorder of a Binary Search Tree (Using Recursion) 1447
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1450
15
Contents
251 Level order traversal in spiral form | Using one stack and one queue 1501
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1503
252 Level order traversal line by line | Set 2 (Using Two Queues) 1504
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1510
253 Level order traversal line by line | Set 3 (Using One Queue) 1511
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1515
254 Level order traversal with direction change after every two levels 1516
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1523
256 Levelwise Alternating GCD and LCM of nodes in Segment Tree 1528
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1536
258 Locking and Unlocking of Resources arranged in the form of n-ary Tree 1543
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1545
16
Contents
267 Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ) 1594
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1600
270 Maximum difference between node and its ancestor in Binary Tree 1613
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1618
271 Maximum edge removal from tree to make even forest 1619
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1622
274 Maximum sum from a tree with adjacent levels not allowed 1632
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1635
275 Maximum sum of nodes in Binary tree such that no two are adjacent 1636
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1640
278 Merge Two Binary Trees by doing Node Sum (Recursive and Iterative) 1667
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1675
280 Minimum no. of iterations to pass information to all nodes in the tree1682
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1689
281 Minimum swap required to convert binary tree to binary search tree 1690
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1691
17
Contents
283 Modify a binary tree to get preorder traversal using right pointers only 1698
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1703
286 Node having maximum sum of immediate children and itself in n-ary
tree 1714
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1717
288 Number of Binary Trees for given Preorder Sequence length 1724
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1728
290 Number of full binary trees such that each node is product of its children 1733
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1741
291 Number of nodes greater than a given value in n-ary tree 1742
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1744
294 Number of turns to reach from one node to other in binary tree 1753
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1761
296 Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) 1767
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1770
18
Contents
302 Perfect Binary Tree Specific Level Order Traversal | Set 2 1810
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1819
305 Possible edges of a tree for given diameter, height and vertices 1833
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1836
308 Postorder traversal of Binary Tree without recursion and without stack 1845
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1848
19
Contents
318 Print Binary Tree levels in sorted order | Set 2 (Using set) 1891
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1893
323 Print Postorder traversal from given Inorder and Preorder traversals 1916
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1921
326 Print a Binary Tree in Vertical Order | Set 2 (Map based Method) 1937
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1944
327 Print a Binary Tree in Vertical Order | Set 3 (Using Level Order
Traversal) 1945
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1952
330 Print all leaf nodes of a Binary Tree from left to right 1960
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1962
20
Contents
333 Print all nodes that are at distance k from a leaf node 1975
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1979
335 Print all root to leaf paths with there relative positions 1986
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1990
336 Print all the paths from root, with a specified sum in Binary tree 1991
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1994
337 Print common nodes on path from root (or common ancestors) 1995
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2000
339 Print cousins of a given node in Binary Tree | Single Traversal 2005
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2011
340 Print extreme nodes of each level of Binary Tree in alternate order 2012
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2015
343 Print middle level of perfect binary tree without finding height 2030
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2034
346 Print nodes between two given level numbers of a binary tree 2044
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2050
348 Print path from root to a given node in a binary tree 2055
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2058
21
Contents
350 Print the longest leaf to leaf path in a Binary tree 2063
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2068
352 Print the path common to the two paths from the root to the two
given nodes 2073
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2078
359 Queries to find distance between two nodes of a Binary tree 2113
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2115
360 Queries to find distance between two nodes of a Binary tree – O(logn)
method 2116
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2124
365 Relationship between number of nodes and height of binary tree 2148
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2150
366 Remove all nodes which don’t lie in any path with sum>= k 2151
22
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2163
368 Replace each node in binary tree with the sum of its inorder prede-
cessor and successor 2170
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2174
377 Root to leaf paths having equal lengths in a Binary Tree 2230
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2232
23
Contents
383 Select a Random Node from a tree with equal probability 2272
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2273
386 Shortest distance between two nodes in an infinite binary tree 2287
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2291
387 Shortest path between two nodes in array like representation of binary
tree 2292
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2295
24
Contents
407 Sum of all the numbers that are formed from root to leaf paths 2399
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2404
408 Sum of all the parent nodes having child node x 2405
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2409
414 Sum of nodes at maximum depth of a Binary Tree | Iterative Approach 2430
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2432
415 Sum of nodes on the longest path from root to leaf node 2433
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2438
25
Contents
425 Total sum except adjacent of a given node in a Binary Tree 2484
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2488
426 Traversal of tree with k jumps allowed between nodes of same height 2489
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2494
26
Contents
434 Ways to color a skewed tree such that parent and child have different
colors 2542
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2547
437 Write a Program to Find the Maximum Depth or Height of a Tree 2560
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2565
439 XOR of numbers that appeared even number of times in given Range 2571
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2576
27
Chapter 1
28
Chapter 1. A program to check if a binary tree is BST or not
This approach is wrong as this will return true for below binary tree (and
below tree is not a BST because 4 is in left subtree of 3)
29
Chapter 1. A program to check if a binary tree is BST or not
It is assumed that you have helper functions minValue() and maxValue() that return the
min or max int value from a non-empty tree
METHOD 3 (Correct and Efficient)
Method 2 above runs slowly since it traverses over some parts of the tree many times. A
better solution looks at each node only once. The trick is to write a utility helper function
isBSTUtil(struct node* node, int min, int max) that traverses down the tree keeping track
of the narrowing min and max allowed values as it goes, looking at each node only once.
The initial values for min and max should be INT_MIN and INT_MAX — they narrow
from there.
Implementation:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
30
Chapter 1. A program to check if a binary tree is BST or not
int isBSTUtil(struct node* node, int min, int max);
/* Returns true if the given tree is a binary search tree
(efficient version). */
int isBST(struct node* node)
{
return(isBSTUtil(node, INT_MIN, INT_MAX));
}
/* Returns true if the given tree is a BST and its
values are >= min and <= max. */
int isBSTUtil(struct node* node, int min, int max)
{
/* an empty tree is BST */
if (node==NULL)
return 1;
/* false if this node violates the min/max constraint */
if (node->data < min || node->data > max)
return 0;
/* otherwise check the subtrees recursively,
tightening the min or max constraint */
return
isBSTUtil(node->left, min, node->data-1) && // Allow only distinct values
isBSTUtil(node->right, node->data+1, max); // Allow only distinct values
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
struct node *root = newNode(4);
root->left = newNode(2);
root->right = newNode(5);
31
Chapter 1. A program to check if a binary tree is BST or not
root->left->left = newNode(1);
root->left->right = newNode(3);
if(isBST(root))
printf("Is BST");
else
printf("Not a BST");
getchar();
return 0;
}
Java
32
Chapter 1. A program to check if a binary tree is BST or not
Python
33
Chapter 1. A program to check if a binary tree is BST or not
self.right = None
# Returns true if the given tree is a binary search tree
# (efficient version)
def isBST(node):
return (isBSTUtil(node, INT_MIN, INT_MAX))
# Retusn true if the given tree is a BST and its values
# >= min and <= max
def isBSTUtil(node, mini, maxi):
# An empty tree is BST
if node is None:
return True
# False if this node violates min/max constraint
if node.data < mini or node.data > maxi:
return False
# Otherwise check the subtrees recursively
# tightening the min or max constraint
return (isBSTUtil(node.left, mini, node.data -1) and
isBSTUtil(node.right, node.data+1, maxi))
# Driver program to test above function
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(3)
if (isBST(root)):
print "Is BST"
else:
print "Not a BST"
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Simplified Method 3
We can simplify method 2 using NULL pointers instead of INT_MIN and INT_MAX values.
34
Chapter 1. A program to check if a binary tree is BST or not
35
Chapter 1. A program to check if a binary tree is BST or not
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(1);
root->left->right = newNode(4);
if (isBST(root,NULL,NULL))
cout << "Is BST";
else
cout << "Not a BST";
return 0;
}
Output :
Not a BST
36
Chapter 1. A program to check if a binary tree is BST or not
return isBST(root->right);
}
return true;
}
Java
37
Chapter 1. A program to check if a binary tree is BST or not
// allows only distinct values node
if (prev != null && node.data <= prev.data )
return false;
prev = node;
return isBST(node.right);
}
return true;
}
/* Driver program to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(4);
tree.root.left = new Node(2);
tree.root.right = new Node(5);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(3);
if (tree.isBST())
System.out.println("IS BST");
else
System.out.println("Not a BST");
}
}
Python3
38
Chapter 1. A program to check if a binary tree is BST or not
def isbst(root):
# prev is a global variable
global prev
prev = None
return isbst_rec(root)
# Helper function to test if binary
# tree is BST
# Traverse the tree in inorder fashion
# and keep track of previous node
# return true if tree is Binary
# search tree otherwise false
def isbst_rec(root):
# prev is a global variable
global prev
# if tree is empty return true
if root is None:
return True
if isbst_rec(root.left) is False:
return False
# if previous node'data is found
# greater than the current node's
# data return fals
if prev is not None and prev.data > root.data:
return False
# store the current node in prev
prev = root
return isbst_rec(root.right)
# driver code to test above function
root = Node(4)
root.left = Node(2)
root.right = Node(5)
root.left.left = Node(1)
root.left.right = Node(3)
if isbst(root):
print("is BST")
else:
print("not a BST")
39
Chapter 1. A program to check if a binary tree is BST or not
# This code is contributed by
# Shweta Singh(shweta44)
The use of static variable can also be avoided by using reference to prev node as a parameter.
40
Chapter 1. A program to check if a binary tree is BST or not
Sources:
http://en.wikipedia.org/wiki/Binary_search_tree
http://cslibrary.stanford.edu/110/BinaryTrees.html
Improved By : shweta44, ChandrahasAbburi
Source
https://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/
41
Chapter 2
Additional storage requirement with every node is O(Log n) in red black trees instead of
O(1) (only color in Red Black Trees), but AA trees simplify restructuring by removing many
cases.
An AA tree follows same rule as red-black trees with the addition of single new rule that
red nodes cannot be present as left child.
Why AA trees :
The implementation and number of rotation cases in Red-Black Trees is complex. AA trees
simplifies the algorithm.
• It eliminates half of the restructuring process by eliminating half of the rotation cases,
which is easier to code.
42
Chapter 2. AA Trees | Set 1 (Introduction)
Note that in the above tree there are no left red child which is the new added rule of AA
Trees.
After re-drawing the above AA tree with levels and horizontal links (the red nodes are shown
connected through horizontal or red links), the tree looks like:
Note that all the nodes on level 1 i.e. 5, 10, 20, 35, 40, 55, 65, 80, 90 are known as leaf
nodes.
So, in summarized way, for tree to be AA tree, it must satisfy the following five
invariants:
Source
https://www.geeksforgeeks.org/aa-trees-set-1-introduction/
43
Chapter 3
The above tree is AVL because differences between heights of left and right subtrees for
every node is less than or equal to 1.
An Example Tree that is NOT an AVL Tree
44
Chapter 3. AVL Tree | Set 1 (Insertion)
The above tree is not AVL because differences between heights of left and right subtrees for
8 and 18 is greater than 1.
Why AVL Trees?
Most of the BST operations (e.g., search, max, min, insert, delete.. etc) take O(h) time
where h is the height of the BST. The cost of these operations may become O(n) for a skewed
Binary tree. If we make sure that height of the tree remains O(Logn) after every insertion
and deletion, then we can guarantee an upper bound of O(Logn) for all these operations.
The height of an AVL tree is always O(Logn) where n is the number of nodes in the tree
(See thisvideo lecture for proof).
Insertion
To make sure that the given tree remains AVL after every insertion, we must augment
the standard BST insert operation to perform some re-balancing. Following are two basic
operations that can be performed to re-balance a BST without violating the BST property
(keys(left) < key(root) < keys(right)). 1) Left Rotation 2) Right Rotation
45
Chapter 3. AVL Tree | Set 1 (Insertion)
z z x
/ \ / \ / \
y T4 Left Rotate (y) x T4 Right Rotate(z) y z
/ \ - - - - - - - - -> / \ - - - - - - - -> / \ / \
T1 x y T3 T1 T2 T3 T4
/ \ / \
T2 T3 T1 T2
z y
/ \ / \
T1 y Left Rotate(z) z x
46
Chapter 3. AVL Tree | Set 1 (Insertion)
/ \ - - - - - - - -> / \ / \
T2 x T1 T2 T3 T4
/ \
T3 T4
z z x
/ \ / \ / \
T1 y Right Rotate (y) T1 x Left Rotate(z) z y
/ \ - - - - - - - - -> / \ - - - - - - - -> / \ / \
x T4 T2 y T1 T2 T3 T4
/ \ / \
T2 T3 T3 T4
Insertion Examples:
47
Chapter 3. AVL Tree | Set 1 (Insertion)
48
Chapter 3. AVL Tree | Set 1 (Insertion)
49
Chapter 3. AVL Tree | Set 1 (Insertion)
implementation
Following is the implementation for AVL Tree Insertion. The following implementation uses
the recursive BST insert to insert a new node. In the recursive BST insert, after insertion,
we get pointers to all ancestors one by one in a bottom-up manner. So we don’t need parent
pointer to travel up. The recursive code itself travels up and visits all the ancestors of the
newly inserted node.
1) Perform the normal BST insertion.
2) The current node must be one of the ancestors of the newly inserted node. Update the
height of the current node.
3) Get the balance factor (left subtree height – right subtree height) of the current node.
4) If balance factor is greater than 1, then the current node is unbalanced and we are either
in Left Left case or left Right case. To check whether it is left left case or not, compare the
newly inserted key with the key in left subtree root.
5) If balance factor is less than -1, then the current node is unbalanced and we are either
in Right Right case or Right-Left case. To check whether it is Right Right case or not,
compare the newly inserted key with the key in right subtree root.
C
50
Chapter 3. AVL Tree | Set 1 (Insertion)
// An AVL tree node
struct Node
{
int key;
struct Node *left;
struct Node *right;
int height;
};
// A utility function to get maximum of two integers
int max(int a, int b);
// A utility function to get the height of the tree
int height(struct Node *N)
{
if (N == NULL)
return 0;
return N->height;
}
// A utility function to get maximum of two integers
int max(int a, int b)
{
return (a > b)? a : b;
}
/* Helper function that allocates a new node with the given key and
NULL left and right pointers. */
struct Node* newNode(int key)
{
struct Node* node = (struct Node*)
malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1; // new node is initially added at leaf
return(node);
}
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
struct Node *rightRotate(struct Node *y)
{
struct Node *x = y->left;
struct Node *T2 = x->right;
// Perform rotation
51
Chapter 3. AVL Tree | Set 1 (Insertion)
x->right = y;
y->left = T2;
// Update heights
y->height = max(height(y->left), height(y->right))+1;
x->height = max(height(x->left), height(x->right))+1;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
struct Node *leftRotate(struct Node *x)
{
struct Node *y = x->right;
struct Node *T2 = y->left;
// Perform rotation
y->left = x;
x->right = T2;
// Update heights
x->height = max(height(x->left), height(x->right))+1;
y->height = max(height(y->left), height(y->right))+1;
// Return new root
return y;
}
// Get Balance factor of node N
int getBalance(struct Node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
// Recursive function to insert a key in the subtree rooted
// with node and returns the new root of the subtree.
struct Node* insert(struct Node* node, int key)
{
/* 1. Perform the normal BST insertion */
if (node == NULL)
return(newNode(key));
if (key < node->key)
node->left = insert(node->left, key);
52
Chapter 3. AVL Tree | Set 1 (Insertion)
53
Chapter 3. AVL Tree | Set 1 (Insertion)
if(root != NULL)
{
printf("%d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}
/* Drier program to test above function*/
int main()
{
struct Node *root = NULL;
/* Constructing tree given in the above figure */
root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 50);
root = insert(root, 25);
/* The constructed AVL Tree would be
30
/ \
20 40
/ \ \
10 25 50
*/
printf("Preorder traversal of the constructed AVL"
" tree is \n");
preOrder(root);
return 0;
}
Java
54
Chapter 3. AVL Tree | Set 1 (Insertion)
class AVLTree {
Node root;
// A utility function to get the height of the tree
int height(Node N) {
if (N == null)
return 0;
return N.height;
}
// A utility function to get maximum of two integers
int max(int a, int b) {
return (a > b) ? a : b;
}
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
Node rightRotate(Node y) {
Node x = y.left;
Node T2 = x.right;
// Perform rotation
x.right = y;
y.left = T2;
// Update heights
y.height = max(height(y.left), height(y.right)) + 1;
x.height = max(height(x.left), height(x.right)) + 1;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
Node leftRotate(Node x) {
Node y = x.right;
Node T2 = y.left;
// Perform rotation
y.left = x;
x.right = T2;
// Update heights
x.height = max(height(x.left), height(x.right)) + 1;
55
Chapter 3. AVL Tree | Set 1 (Insertion)
56
Chapter 3. AVL Tree | Set 1 (Insertion)
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node.right.key) {
node.right = rightRotate(node.right);
return leftRotate(node);
}
/* return the (unchanged) node pointer */
return node;
}
// A utility function to print preorder traversal
// of the tree.
// The function also prints height of every node
void preOrder(Node node) {
if (node != null) {
System.out.print(node.key + " ");
preOrder(node.left);
preOrder(node.right);
}
}
public static void main(String[] args) {
AVLTree tree = new AVLTree();
/* Constructing tree given in the above figure */
tree.root = tree.insert(tree.root, 10);
tree.root = tree.insert(tree.root, 20);
tree.root = tree.insert(tree.root, 30);
tree.root = tree.insert(tree.root, 40);
tree.root = tree.insert(tree.root, 50);
tree.root = tree.insert(tree.root, 25);
/* The constructed AVL Tree would be
30
/ \
20 40
/ \ \
10 25 50
*/
System.out.println("Preorder traversal" +
" of constructed tree is : ");
tree.preOrder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal
57
Chapter 3. AVL Tree | Set 1 (Insertion)
Python3
58
Chapter 3. AVL Tree | Set 1 (Insertion)
59
Chapter 3. AVL Tree | Set 1 (Insertion)
Output:
60
Chapter 3. AVL Tree | Set 1 (Insertion)
Time Complexity: The rotation operations (left and right rotate) take constant time as
only a few pointers are being changed there. Updating the height and getting the balance
factor also takes constant time. So the time complexity of AVL insert remains same as BST
insert which is O(h) where h is the height of the tree. Since AVL tree is balanced, the height
is O(Logn). So time complexity of AVL insert is O(Logn).
Comparison with Red Black Tree
The AVL tree and other self-balancing search trees like Red Black are useful to get all basic
operations done in O(log n) time. The AVL trees are more balanced compared to Red-
Black Trees, but they may cause more rotations during insertion and deletion. So if your
application involves many frequent insertions and deletions, then Red Black trees should
be preferred. And if the insertions and deletions are less frequent and search is the more
frequent operation, then AVL tree should be preferred overRed Black Tree.
Following is the post for delete.
AVL Tree | Set 2 (Deletion)
Following are some posts that have used self-balancing search trees.
Median in a stream of integers (running integers)
Maximum of all subarrays of size k
Count smaller elements on right side
References:
IITD Video Lecture on AVL Tree Introduction
IITD Video Lecture on AVL Tree Insertion and Deletion
Source
https://www.geeksforgeeks.org/avl-tree-set-1-insertion/
61
Chapter 4
T1, T2 and T3 are subtrees of the tree rooted with y (on left side)
or x (on right side)
y x
/ \ Right Rotation / \
x T3 – - – - – - – > T1 y
/ \ < - - - - - - - / \
T1 T2 Left Rotation T2 T3
Keys in both of the above trees follow the following order
keys(T1) < key(x) < keys(T2) < key(y) < keys(T3)
So BST property is not violated anywhere.
62
Chapter 4. AVL Tree | Set 2 (Deletion)
z z x
/ \ / \ / \
y T4 Left Rotate (y) x T4 Right Rotate(z) y z
/ \ - - - - - - - - -> / \ - - - - - - - -> / \ / \
T1 x y T3 T1 T2 T3 T4
/ \ / \
T2 T3 T1 T2
z y
/ \ /
\
T1 y Left Rotate(z) z x
/ \ - - - - - - - -> / \ / \
T2 x T1 T2 T3 T4
/ \
T3 T4
63
Chapter 4. AVL Tree | Set 2 (Deletion)
z z x
/ \ / \ / \
T1 y Right Rotate (y) T1 x Left Rotate(z) z x
/ \ - - - - - - - - -> / \ - - - - - - - -> / \ / \
x T4 T2 y T1 T2 T3 T4
/ \ / \
T2 T3 T3 T4
64
Chapter 4. AVL Tree | Set 2 (Deletion)
A node with value 32 is being deleted. After deleting 32, we travel up and find the first
unbalanaced node which is 44. We mark it as z, its higher height child as y which is 52, and
y’s higher height child as x which could be either 78 or 50 as both are of same height. We
have considered 78. Now the case is Right Right, so we perform left rotation.
C implementation
Following is the C implementation for AVL Tree Deletion. The following C implementation
uses the recursive BST delete as basis. In the recursive BST delete, after deletion, we get
pointers to all ancestors one by one in bottom up manner. So we don’t need parent pointer
to travel up. The recursive code itself travels up and visits all the ancestors of the deleted
node.
1) Perform the normal BST deletion.
2) The current node must be one of the ancestors of the deleted node. Update the height
of the current node.
3) Get the balance factor (left subtree height – right subtree height) of the current node.
4) If balance factor is greater than 1, then the current node is unbalanced and we are either
65
Chapter 4. AVL Tree | Set 2 (Deletion)
in Left Left case or Left Right case. To check whether it is Left Left case or Left Right case,
get the balance factor of left subtree. If balance factor of the left subtree is greater than or
equal to 0, then it is Left Left case, else Left Right case.
5) If balance factor is less than -1, then the current node is unbalanced and we are either
in Right Right case or Right Left case. To check whether it is Right Right case or Right
Left case, get the balance factor of right subtree. If the balance factor of the right subtree
is smaller than or equal to 0, then it is Right Right case, else Right Left case.
C
66
Chapter 4. AVL Tree | Set 2 (Deletion)
67
Chapter 4. AVL Tree | Set 2 (Deletion)
}
struct Node* insert(struct Node* node, int key)
{
/* 1. Perform the normal BST rotation */
if (node == NULL)
return(newNode(key));
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
else // Equal keys not allowed
return node;
/* 2. Update height of this ancestor node */
node->height = 1 + max(height(node->left),
height(node->right));
/* 3. Get the balance factor of this ancestor
node to check whether this node became
unbalanced */
int balance = getBalance(node);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (balance > 1 && key < node->left->key)
return rightRotate(node);
// Right Right Case
if (balance < -1 && key > node->right->key)
return leftRotate(node);
// Left Right Case
if (balance > 1 && key > node->left->key)
{
node->left = leftRotate(node->left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node->right->key)
{
node->right = rightRotate(node->right);
return leftRotate(node);
}
68
Chapter 4. AVL Tree | Set 2 (Deletion)
69
Chapter 4. AVL Tree | Set 2 (Deletion)
// No child case
if (temp == NULL)
{
temp = root;
root = NULL;
}
else // One child case
*root = *temp; // Copy the contents of
// the non-empty child
free(temp);
}
else
{
// node with two children: Get the inorder
// successor (smallest in the right subtree)
struct Node* temp = minValueNode(root->right);
// Copy the inorder successor's data to this node
root->key = temp->key;
// Delete the inorder successor
root->right = deleteNode(root->right, temp->key);
}
}
// If the tree had only one node then return
if (root == NULL)
return root;
// STEP 2: UPDATE HEIGHT OF THE CURRENT NODE
root->height = 1 + max(height(root->left),
height(root->right));
// STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to
// check whether this node became unbalanced)
int balance = getBalance(root);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);
// Left Right Case
if (balance > 1 && getBalance(root->left) < 0)
{
root->left = leftRotate(root->left);
70
Chapter 4. AVL Tree | Set 2 (Deletion)
return rightRotate(root);
}
// Right Right Case
if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);
// Right Left Case
if (balance < -1 && getBalance(root->right) > 0)
{
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
// A utility function to print preorder traversal of
// the tree.
// The function also prints height of every node
void preOrder(struct Node *root)
{
if(root != NULL)
{
printf("%d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}
/* Driver program to test above function*/
int main()
{
struct Node *root = NULL;
/* Constructing tree given in the above figure */
root = insert(root, 9);
root = insert(root, 5);
root = insert(root, 10);
root = insert(root, 0);
root = insert(root, 6);
root = insert(root, 11);
root = insert(root, -1);
root = insert(root, 1);
root = insert(root, 2);
/* The constructed AVL Tree would be
9
71
Chapter 4. AVL Tree | Set 2 (Deletion)
/ \
1 10
/ \ \
0 5 11
/ / \
-1 2 6
*/
printf("Preorder traversal of the constructed AVL "
"tree is \n");
preOrder(root);
root = deleteNode(root, 10);
/* The AVL Tree after deletion of 10
1
/ \
0 9
/ / \
-1 5 11
/ \
2 6
*/
printf("\nPreorder traversal after deletion of 10 \n");
preOrder(root);
return 0;
}
Java
72
Chapter 4. AVL Tree | Set 2 (Deletion)
Node root;
// A utility function to get height of the tree
int height(Node N)
{
if (N == null)
return 0;
return N.height;
}
// A utility function to get maximum of two integers
int max(int a, int b)
{
return (a > b) ? a : b;
}
// A utility function to right rotate subtree rooted with y
// See the diagram given above.
Node rightRotate(Node y)
{
Node x = y.left;
Node T2 = x.right;
// Perform rotation
x.right = y;
y.left = T2;
// Update heights
y.height = max(height(y.left), height(y.right)) + 1;
x.height = max(height(x.left), height(x.right)) + 1;
// Return new root
return x;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
Node leftRotate(Node x)
{
Node y = x.right;
Node T2 = y.left;
// Perform rotation
y.left = x;
x.right = T2;
// Update heights
x.height = max(height(x.left), height(x.right)) + 1;
73
Chapter 4. AVL Tree | Set 2 (Deletion)
74
Chapter 4. AVL Tree | Set 2 (Deletion)
node.left = leftRotate(node.left);
return rightRotate(node);
}
// Right Left Case
if (balance < -1 && key < node.right.key)
{
node.right = rightRotate(node.right);
return leftRotate(node);
}
/* return the (unchanged) node pointer */
return node;
}
/* Given a non-empty binary search tree, return the
node with minimum key value found in that tree.
Note that the entire tree does not need to be
searched. */
Node minValueNode(Node node)
{
Node current = node;
/* loop down to find the leftmost leaf */
while (current.left != null)
current = current.left;
return current;
}
Node deleteNode(Node root, int key)
{
// STEP 1: PERFORM STANDARD BST DELETE
if (root == null)
return root;
// If the key to be deleted is smaller than
// the root's key, then it lies in left subtree
if (key < root.key)
root.left = deleteNode(root.left, key);
// If the key to be deleted is greater than the
// root's key, then it lies in right subtree
else if (key > root.key)
root.right = deleteNode(root.right, key);
// if key is same as root's key, then this is the node
// to be deleted
75
Chapter 4. AVL Tree | Set 2 (Deletion)
else
{
// node with only one child or no child
if ((root.left == null) || (root.right == null))
{
Node temp = null;
if (temp == root.left)
temp = root.right;
else
temp = root.left;
// No child case
if (temp == null)
{
temp = root;
root = null;
}
else // One child case
root = temp; // Copy the contents of
// the non-empty child
}
else
{
// node with two children: Get the inorder
// successor (smallest in the right subtree)
Node temp = minValueNode(root.right);
// Copy the inorder successor's data to this node
root.key = temp.key;
// Delete the inorder successor
root.right = deleteNode(root.right, temp.key);
}
}
// If the tree had only one node then return
if (root == null)
return root;
// STEP 2: UPDATE HEIGHT OF THE CURRENT NODE
root.height = max(height(root.left), height(root.right)) + 1;
// STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether
// this node became unbalanced)
int balance = getBalance(root);
76
Chapter 4. AVL Tree | Set 2 (Deletion)
77
Chapter 4. AVL Tree | Set 2 (Deletion)
Python3
78
Chapter 4. AVL Tree | Set 2 (Deletion)
self.height = 1
# AVL tree class which supports insertion,
# deletion operations
class AVL_Tree(object):
def insert(self, root, key):
# Step 1 - Perform normal BST
if not root:
return TreeNode(key)
elif key < root.val:
root.left = self.insert(root.left, key)
else:
root.right = self.insert(root.right, key)
# Step 2 - Update the height of the
# ancestor node
root.height = 1 + max(self.getHeight(root.left),
self.getHeight(root.right))
# Step 3 - Get the balance factor
balance = self.getBalance(root)
# Step 4 - If the node is unbalanced,
# then try out the 4 cases
# Case 1 - Left Left
if balance > 1 and key < root.left.val:
return self.rightRotate(root)
# Case 2 - Right Right
if balance < -1 and key > root.right.val:
return self.leftRotate(root)
# Case 3 - Left Right
if balance > 1 and key > root.left.val:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)
# Case 4 - Right Left
if balance < -1 and key < root.right.val:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
# Recursive function to delete a node with
# given key from subtree with given root.
79
Chapter 4. AVL Tree | Set 2 (Deletion)
80
Chapter 4. AVL Tree | Set 2 (Deletion)
81
Chapter 4. AVL Tree | Set 2 (Deletion)
# Return the new root
return y
def getHeight(self, root):
if not root:
return 0
return root.height
def getBalance(self, root):
if not root:
return 0
return self.getHeight(root.left) - self.getHeight(root.right)
def getMinValueNode(self, root):
if root is None or root.left is None:
return root
return self.getMinValueNode(root.left)
def preOrder(self, root):
if not root:
return
print("{0} ".format(root.val), end="")
self.preOrder(root.left)
self.preOrder(root.right)
myTree = AVL_Tree()
root = None
nums = [9, 5, 10, 0, 6, 11, -1, 1, 2]
for num in nums:
root = myTree.insert(root, num)
# Preorder Traversal
print("Preorder Traversal after insertion -")
myTree.preOrder(root)
print()
# Delete
key = 10
root = myTree.delete(root, key)
82
Chapter 4. AVL Tree | Set 2 (Deletion)
# Preorder Traversal
print("Preorder Traversal after deletion -")
myTree.preOrder(root)
print()
# This code is contributed by Ajitesh Pathak
Output:
Time Complexity: The rotation operations (left and right rotate) take constant time as
only few pointers are being changed there. Updating the height and getting the balance
factor also take constant time. So the time complexity of AVL delete remains same as BST
delete which is O(h) where h is height of the tree. Since AVL tree is balanced, the height is
O(Logn). So time complexity of AVL delete is O(Log n).
References:
https://www.cs.purdue.edu/homes/ayg/CS251/slides/chap7b.pdf
IITD Video Lecture on AVL Tree Insertion and Deletion
Improved By : AnkushRodewad, KP1975
Source
https://www.geeksforgeeks.org/avl-tree-set-2-deletion/
83
Chapter 5
12(3)
/ \
10(2) 20(1)
/ \
9(1) 11(1)
84
Chapter 5. AVL with duplicate keys
85
Chapter 5. AVL with duplicate keys
86
Chapter 5. AVL with duplicate keys
87
Chapter 5. AVL with duplicate keys
88
Chapter 5. AVL with duplicate keys
89
Chapter 5. AVL with duplicate keys
Output:
90
Chapter 5. AVL with duplicate keys
Thanks to Rounaq Jhunjhunu Wala for sharing initial code. Please write comments if
you find anything incorrect, or you want to share more information about the topic discussed
above
Source
https://www.geeksforgeeks.org/avl-with-duplicate-keys/
91
Chapter 6
50
/ \
30 70
/ \ / \
20 40 60 80
260
/ \
330 150
/ \ / \
350 300 210 80
A simple method for solving this is to find sum of all greater values for every node. This
method would take O(n^2) time.
We can do it using a single traversal. The idea is to use following BST property. If we
do reverse Inorder traversal of BST, we get all nodes in decreasing order. We do reverse
Inorder traversal and keep track of the sum of all nodes visited so far, we add this sum to
every node.
C
92
Chapter 6. Add all greater values to every node in a given BST
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *left, *right;
};
// A utility function to create a new BST node
struct Node *newNode(int item)
{
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
// Recursive function to add all greater values in every node
void modifyBSTUtil(struct Node *root, int *sum)
{
// Base Case
if (root == NULL) return;
// Recur for right subtree
modifyBSTUtil(root->right, sum);
// Now *sum has sum of nodes in right subtree, add
// root->data to sum and update root->data
*sum = *sum + root->data;
root->data = *sum;
// Recur for left subtree
modifyBSTUtil(root->left, sum);
}
// A wrapper over modifyBSTUtil()
void modifyBST(struct Node *root)
{
int sum = 0;
modifyBSTUtil(root, &sum);
}
// A utility function to do inorder traversal of BST
void inorder(struct Node *root)
{
if (root != NULL)
{
93
Chapter 6. Add all greater values to every node in a given BST
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
/* A utility function to insert a new node with given data in BST */
struct Node* insert(struct Node* node, int data)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(data);
/* Otherwise, recur down the tree */
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);
/* return the (unchanged) node pointer */
return node;
}
// Driver Program to test above functions
int main()
{
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
struct Node *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
modifyBST(root);
// print inoder tarversal of the modified BST
inorder(root);
return 0;
}
94
Chapter 6. Add all greater values to every node in a given BST
Java
95
Chapter 6. Add all greater values to every node in a given BST
96
Chapter 6. Add all greater values to every node in a given BST
// A wrapper over modifyBSTUtil()
void modifyBST(Node node)
{
Sum S = new Sum();
this.modifyBSTUtil(node, S);
}
// Driver Function
public static void main(String[] args)
{
BinarySearchTree tree = new BinarySearchTree();
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
tree.modifyBST(tree.root);
// print inoder tarversal of the modified BST
tree.inorder();
}
}
// This code is contributed by Kamal Rawal
Output
97
Chapter 6. Add all greater values to every node in a given BST
Source
https://www.geeksforgeeks.org/add-greater-values-every-node-given-bst/
98
Chapter 7
1. With Trie, we can insert and find strings in O(L) time where L represent the length
of a single word. This is obviously faster that BST. This is also faster than Hashing
because of the ways it is implemented. We do not need to compute any hash function.
No collision handling is required (like we do in open addressing and separate chaining)
2. Another advantage of Trie is, we can easily print all words in alphabetical orderwhich
is not easily possible with hashing.
3. We can efficiently doprefix search (or auto-complete) with Trie.
99
Chapter 7. Advantages of Trie Data Structure
height of the tree. Ternary Search Trees also supports other operations supported by Trie
like prefix search, alphabetical order printing and nearest neighbor search.
The final conclusion is regarding tries data structure is that they are faster but require huge
memory for storing the strings.
Improved By : Aashutosh Rathi
Source
https://www.geeksforgeeks.org/advantages-trie-data-structure/
100
Chapter 8
Applications of Minimum
Spanning Tree Problem
101
Chapter 8. Applications of Minimum Spanning Tree Problem
Indirect applications.
– max bottleneck paths
– LDPC codes for error correction
– image registration with Renyi entropy
– learning salient features for real-time face verification
– reducing data storage in sequencing amino acids in a protein
– model locality of particle interactions in turbulent fluid flows
– autoconfig protocol for Ethernet bridging to avoid cycles in a network
Cluster analysis
k clustering problem can be viewed as finding an MST and deleting the k-1 most
expensive edges.
Sources:
http://www.cs.princeton.edu/courses/archive/spr07/cos226/lectures/mst.pdf
http://www.ics.uci.edu/~eppstein/161/960206.html
Source
https://www.geeksforgeeks.org/applications-of-minimum-spanning-tree/
102
Chapter 9
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:
file system
———–
/ <-- root
/ \
... home
/ \
ugrad course
/ / | \
... cs101 cs112 cs113
2. If we organize keys in form of a tree (with some ordering e.g., BST), we can search
for a given key in moderate time (quicker than Linked List and slower than arrays).
Self-balancing search treeslike AVL and Red-Black trees guarantee an upper bound of
O(Logn) for search.
3. We can insert/delete keys in moderate time (quicker than Arrays and slower than
Unordered Linked Lists). Self-balancing search treeslike AVL and Red-Black trees
guarantee an upper bound of O(Logn) for insertion/deletion.
103
Chapter 9. Applications of tree data structure
4. Like Linked Lists and unlike Arrays, Pointer implementation of trees don’t have an
upper limit on number of nodes as nodes are linked using pointers.
Other Applications :
1. Heap is a tree data structure which is implemented using arrays and used to implement
priority queues.
2. B-Tree andB+ Tree : They are used to implement indexing in databases.
3. Syntax Tree: Used in Compilers.
4. K-D Tree: A space partitioning tree used to organize points in K dimensional space.
5. Trie : Used to implement dictionaries with prefix lookup.
6. Suffix Tree : For quick pattern searching in a fixed text.
Source
https://www.geeksforgeeks.org/applications-of-tree-data-structure/
104
Chapter 10
Input :
4
/ \
2 9
/ \ \
3 5 7
Output : [4 5.5 5]
The average value of nodes on level 0 is 4,
on level 1 is 5.5, and on level 2 is 5.
Hence, print [4 5.5 5].
The idea is based on Level order traversal line by line | Set 2 (Using Two Queues)
1. Start by pushing the root node into the queue. Then, remove a node from the front
of the queue.
2. For every node removed from the queue, push all its children into a new temporary
queue.
3. Keep on popping nodes from the queue and adding these node’ s children to the
temporary queue till queue becomes empty.
4. Every time queue becomes empty, it indicates that one level of the tree has been
considered.
105
Chapter 10. Averages of Levels in Binary Tree
5. While pushing the nodes into temporary queue, keep a track of the sum of the nodes
along with the number of nodes pushed and find out the average of the nodes on each
level by making use of these sum and count values.
6. After each level has been considered, again initialize the queue with temporary queue
and continue the process till both queues become empty.
106
Chapter 10. Averages of Levels in Binary Tree
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node* newNode(int data)
{
Node* temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver code
int main()
{
/* Let us construct a Binary Tree
4
/ \
2 9
/ \ \
3 5 7 */
Node* root = NULL;
root = newNode(4);
root->left = newNode(2);
root->right = newNode(9);
root->left->left = newNode(3);
root->left->right = newNode(8);
root->right->right = newNode(7);
averageOfLevels(root);
return 0;
}
Output:
Average of levels:
[4 5.5 5]
Complexity Analysis:
107
Chapter 10. Averages of Levels in Binary Tree
Source
https://www.geeksforgeeks.org/averages-levels-binary-tree/
108
Chapter 11
109
Chapter 11. BFS vs DFS for Binary Tree
Why do we care?
There are many tree questions that can be solved using any of the above four traversals.
Examples of such questions are size, maximum, minimum, print left view, etc.
Is there any difference in terms of Time Complexity?
All four traversals require O(n) time as they visit every node exactly once.
Is there any difference in terms of Extra Space?
There is difference in terms of extra space required.
1. Extra Space required for Level Order Traversal is O(w) where w is maximum width of
Binary Tree. In level order traversal, queue one by one stores nodes of different level.
2. Extra Space required for Depth First Traversals is O(h) where h is maximum height
of Binary Tree. In Depth First Traversals, stack (or function call stack) stores all
ancestors of a node.
Maximum Width of a Binary Tree at depth (or height) h can be 2h where h starts from 0.
So the maximum number of nodes can be at the last level. And worst case occurs when
Binary Tree is a perfect Binary Tree with numbers of nodes like 1, 3, 7, 15, …etc. In worst
case, value of 2h is Ceil(n/2).
Height for a Balanced Binary Tree is O(Log n). Worst case occurs for skewed tree and worst
case height becomes O(n).
So in worst case extra space required is O(n) for both. But worst cases occur for different
types of trees.
It is evident from above points that extra space required for Level order traversal
is likely to be more when tree is more balanced and extra space for Depth First
Traversal is likely to be more when tree is less balanced.
How to Pick One?
Exercise:
Which traversal should be used to print leaves of Binary Tree and why?
Which traversal should be used to print nodes at k’th level where k is much less than total
number of levels?
This article is contributed by Dheeraj Gupta. This Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/bfs-vs-dfs-binary-tree/
110
Chapter 12
Let’s say we have a dictionary of words and then we have some other words which are to
be checked in the dictionary for spelling errors. We need to have collection of all words in
the dictionary which are very close to the given word. For instance if we are checking a
word “ruk” we will have {“truck”,”buck”,”duck”,……}. Therefore, spelling mistake can
be corrected by deleting a character from the word or adding a new character in the word
or by replacing the character in the word by some appropriate one. Therefore, we will be
using the edit distance as a measure for correctness and matching of the misspelled word
from the words in our dictionary.
Now, let’s see the structure of our BK Tree. Like all other trees, BK Tree consists of nodes
and edges. The nodes in the BK Tree will represent the individual words in our dictionary
and there will be exactly the same number of nodes as the number of words in our dictionary.
The edge will contain some integer weight that will tell us about the edit-distance from one
node to another. Lets say we have an edge from node u to node v having some edge-weight
w, then w is the edit-distance required to turn the string u to v.
Consider our dictionary with words : { “help” , “hell” , “hello”}. Therefore, for this
dictionary our BK Tree will look like the below one.
111
Chapter 12. BK-Tree | Introduction & Implementation
Every node in the BK Tree will have exactly one child with same edit-distance. In case,
if we encounter some collision for edit-distance while inserting, we will then propagate the
insertion process down the children until we find an appropriate parent for the string node.
Every insertion in the BK Tree will start from our root node. Root node can be any word
from our dictionary.
For example, let’s add another word “shell” to the above dictionary. Now our Dict[] =
{“help” , “hell” , “hello” , “shell”}. It is now evident that “shell” has same edit-
distance as “hello” has from the root node “help” i.e 2. Hence, we encounter a collision.
Therefore, we deal this collision by recursively doing this insertion process on the pre-existing
colliding node.
So, now instead of inserting “shell” at the root node “help“, we will now insert it to the
colliding node “hello“. Therefore, now the new node “shell” is added to the tree and it
has node “hello” as its parent with the edge-weigth of 2(edit-distance). Below pictorial
representation describes the BK Tree after this insertion.
112
Chapter 12. BK-Tree | Introduction & Implementation
So, till now we have understood how we will build our BK Tree. Now, the question arises
that how to find the closest correct word for our misspelled word? First of all, we need
to set a tolerance value. This tolerance value is simply the maximum edit distance from
our misspelled word to the correct words in our dictionary. So, to find the eligible correct
words within the tolerance limit, Naive approach will be to iterate over all the words in the
dictionary and collect the words which are within the tolerance limit. But this approach has
O(n*m*n) time complexity(n is the number of words in dict[] , m is average size of correct
word and n is length of misspelled word) which times out for larger size of dictionary.
Therefore, now the BK Tree comes into action. As we know that each node in BK Tree is
constructed on basis of edit-distance measure from its parent. Therefore, we will directly
113
Chapter 12. BK-Tree | Introduction & Implementation
be going from root node to specific nodes that lie within the tolerance limit. Lets, say our
tolerance limit is TOL and the edit-distance of the current node from the misspelled word
is dist. Therefore, now instead of iterating over all its children we will only iterate over its
children that have edit distance in range
[dist-TOL , dist+TOL]. This will reduce our complexity by a large extent. We will discuss
this in our time complexity analysis.
Consider the below constructed BK Tree.
Let’s say we have a misspelled word “oop” and the tolerance limit is 2. Now, we will see
how we will collect the expected correct for the given misspelled word.
Iteration 1: We will start checking the edit distance from the root node. D(“oop” -> “help”)
114
Chapter 12. BK-Tree | Introduction & Implementation
= 3. Now we will iterate over its children having edit distance in range [ D-TOL , D+TOL
] i.e [1,5]
Iteration 2: Let’s start iterating from the highest possible edit distance child i.e node “loop”
with edit distance 4.Now once again we will find its edit distance from our misspelled word.
D(“oop”,”loop”) = 1.
here D = 1 i.e D <= TOL , so we will add ”loop” to the expected correct word list and
process its child nodes having edit distance in range [D-TOL,D+TOL] i.e [1,3]
Iteration 3: Now, we are at node ”troop” . Once again we will check its edit distance from
misspelled word . D(”oop”,”troop”)=2 .Here again D <= TOL , hence again we will add
”troop” to the expected correct word list.
We will proceed the same for all the words in the range [D-TOL,D+TOL] starting from the
root node till the bottom most leaf node. This, is similar to a DFS traversal on a tree, with
selectively visiting the child nodes whose edge weight lie in some given range.
Therefore, at the end we will be left with only 2 expected words for the misspelled word
”oop” i.e {”loop”,”troop”}
115
Chapter 12. BK-Tree | Introduction & Implementation
};
// stores the root Node
Node RT;
// stores every Node of the tree
Node tree[MAXN];
// index for current Node of tree
int ptr;
int min(int a, int b, int c)
{
return min(a, min(b, c));
}
// Edit Distance
// Dynamic-Approach O(m*n)
int editDistance(string& a,string& b)
{
int m = a.length(), n = b.length();
int dp[m+1][n+1];
// filling base cases
for (int i=0; i<=m; i++)
dp[i][0] = i;
for (int j=0; j<=n; j++)
dp[0][j] = j;
// populating matrix using dp-approach
for (int i=1; i<=m; i++)
{
for (int j=1; j<=n; j++)
{
if (a[i-1] != b[j-1])
{
dp[i][j] = min( 1 + dp[i-1][j], // deletion
1 + dp[i][j-1], // insertion
1 + dp[i-1][j-1] // replacement
);
}
else
dp[i][j] = dp[i-1][j-1];
}
}
return dp[m][n];
}
116
Chapter 12. BK-Tree | Introduction & Implementation
117
Chapter 12. BK-Tree | Introduction & Implementation
118
Chapter 12. BK-Tree | Introduction & Implementation
Output:
Time Complexity : It is quite evident that the time complexity majorly depends on the
tolerance limit. We will be considering tolerance limit to be 2. Now, roughly estimating,
the depth of BK Tree will be log n, where n is the size of dictionary. At every level we
are visiting 2 nodes in the tree and performing edit distance calculation. Therefore, our
Time Complexity will be O(L1*L2*log n), here L1 is the average length of word in our
dictionary and L2 is the length of misspelled. Generally L1 and L2 will be small.
References
• https://en.wikipedia.org/wiki/BK-tree
• https://issues.apache.org/jira/browse/LUCENE-2230
Source
https://www.geeksforgeeks.org/bk-tree-introduction-implementation/
119
Chapter 13
Given above BST with N=5 Nodes. The values at Node being 9, 6, 15, 3, 21
Binary Tree after convertion
120
Chapter 13. BST to a Tree with sum of all smaller keys
Binary Tree after convertion, the values at Node being 18, 9, 33, 3, 54
Solution: We will perform a regular Inorder traversal in which we keep track of sum of
Nodes visited. Let this sum be sum. The Node which is being visited, add that key of
Node to sum i.e. sum = sum + Node->key. Change the key of current Node to sum i.e.
Node->key = sum.
When a BST is being traversed in inorder, for every key currently being visited, all keys
that are already visited are all smaller keys.
C++
121
Chapter 13. BST to a Tree with sum of all smaller keys
}
// A recursive function that traverses the
// given BST in inorder and for every key,
// adds all smaller keys to it
void addSmallerUtil(struct Node* root, int* sum)
{
// Base Case
if (root == NULL)
return;
// Recur for left subtree first so that
// sum of all smaller Nodes is stored
addSmallerUtil(root->left, sum);
// Update the value at sum
*sum = *sum + root->key;
// Update key of this Node
root->key = *sum;
// Recur for right subtree so that
// the updated sum is added
// to greater Nodes
addSmallerUtil(root->right, sum);
}
// A wrapper over addSmallerUtil(). It
// initializes sum and calls addSmallerUtil()
// to recursively update and use value of
void addSmaller(struct Node* root)
{
int sum = 0;
addSmallerUtil(root, &sum);
}
// A utility function to print inorder
// traversal of Binary Tree
void printInorder(struct Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->key);
printInorder(node->right);
}
// Driver program to test above function
122
Chapter 13. BST to a Tree with sum of all smaller keys
int main()
{
/* Create following BST
9
/ \
6 15 */
Node* root = newNode(9);
root->left = newNode(6);
root->right = newNode(15);
printf(" Original BST\n");
printInorder(root);
addSmaller(root);
printf("\n BST To Binary Tree\n");
printInorder(root);
return 0;
}
Java
123
Chapter 13. BST to a Tree with sum of all smaller keys
// A recursive function that traverses
// the given BST in inorder and for every
// key, adds all smaller keys to it
void addSmallerUtil(Node node, Sum sum)
{
// Base Case
if (node == null) {
return;
}
// Recur for left subtree first so that
// sum of all smaller Nodes is stored at sum
addSmallerUtil(node.left, sum);
// Update the value at sum
sum.addvalue = sum.addvalue + node.data;
// Update key of this Node
node.data = sum.addvalue;
// Recur for right subtree so that the
// updated sum is added to greater Nodes
addSmallerUtil(node.right, sum);
}
// A wrapper over addSmallerUtil(). It
// initializes addvalue and calls
// addSmallerUtil() to recursively update
// and use value of addvalue
Node addSmaller(Node node)
{
addSmallerUtil(node, add);
return node;
}
// A utility function to print inorder
// traversal of Binary Tree
void printInorder(Node node)
{
if (node == null) {
return;
}
printInorder(node.left);
System.out.print(node.data + " ");
printInorder(node.right);
}
124
Chapter 13. BST to a Tree with sum of all smaller keys
// Driver program to test the above functions
public static void main(String[] args)
{
BSTtoBinaryTree tree = new BSTtoBinaryTree();
tree.root = new Node(9);
tree.root.left = new Node(6);
tree.root.right = new Node(15);
System.out.println("Original BST");
tree.printInorder(root);
Node Node = tree.addSmaller(root);
System.out.println("");
System.out.println("BST To Binary Tree");
tree.printInorder(Node);
}
}
Source
https://www.geeksforgeeks.org/bst-tree-sum-smaller-keys/
125
Chapter 14
Output: Element at 3 is 2
Element at 3 is 5
126
Chapter 14. Binary Indexed Tree : Range Updates and Point Queries
1. update(l, r, val) : Iterate over the subarray from l to r and increase all the elements
by val.
2. getElement(i) : To get the element at i’th index, simply return arr[i].
The time complexity in worst case is O(q*n) where q is number of queries and n is number
of elements.
1. update(l, r, val) : Add ‘val’ to the lth element and subtract ‘val’ from the (r+1)th
element, do this for all the update queries.
2. getElement(i) : To get ith element in the array find the sum of all integers in the
array from 0 to i.(Prefix Sum).
Let’s analyze the update query. Why to add val to lth index? Adding val to lth index
means that all the elements after l are increased by val, since we will be computing the prefix
sum for every element. Why to subtract val from (r+1)th index? A range update was
required from [l,r] but what we have updated is [l, n-1] so we need to remove val from all
the elements after r i.e., subtract val from (r+1)th index. Thus the val is added to range
[l,r]. Below is implementation of above approach.
C++
// C++ program to demonstrate Range Update // and Point Queries Without using BIT #include <iost
Output:
Element at index 4 is 2
Element at index 3 is 6
C++
127
Chapter 14. Binary Indexed Tree : Range Updates and Point Queries
128
Chapter 14. Binary Indexed Tree : Range Updates and Point Queries
129
Chapter 14. Binary Indexed Tree : Range Updates and Point Queries
update(BITree, l, r, n, val);
// Find the element at Index 3
index = 3;
cout << "Element at index " << index << " is " <<
getSum(BITree,index) << "\n" ;
return 0;
}
Java
130
Chapter 14. Binary Indexed Tree : Range Updates and Point Queries
}
}
// Constructs Binary Indexed Tree
// for given array of size n.
public static void constructBITree(int arr[],
int n)
{
// Initialize BITree[] as 0
for(int i = 1; i <= n; i++)
BITree[i] = 0;
// Store the actual values
// in BITree[] using update()
for(int i = 0; i < n; i++)
updateBIT(n, i, arr[i]);
// Uncomment below lines to
// see contents of BITree[]
// for (int i=1; i<=n; i++)
// cout << BITree[i] << " ";
}
// SERVES THE PURPOSE OF getElement()
// Returns sum of arr[0..index]. This
// function assumes that the array is
// preprocessed and partial sums of
// array elements are stored in BITree[]
public static int getSum(int index)
{
int sum = 0; //Initialize result
// index in BITree[] is 1 more
// than the index in arr[]
index = index + 1;
// Traverse ancestors
// of BITree[index]
while (index > 0)
{
// Add current element
// of BITree to sum
sum += BITree[index];
// Move index to parent
// node in getSum View
131
Chapter 14. Binary Indexed Tree : Range Updates and Point Queries
132
Chapter 14. Binary Indexed Tree : Range Updates and Point Queries
// at Index 3
index = 3;
System.out.println("Element at index "+
index + " is "+
getSum(index));
}
}
// This code is contributed
// by Puneet Kumar.
Output:
Element at index 4 is 2
Element at index 3 is 6
Source
https://www.geeksforgeeks.org/binary-indexed-tree-range-updates-point-queries/
133
Chapter 15
A(0)
/ \
B(1) C(2)
/ \ \
D(3) E(4) F(5)
OR,
A(1)
/ \
B(2) C(3)
/ \ \
D(4) E(5) F(6)
134
Chapter 15. Binary Tree (Array implementation)
and right_son=(2*p)+1;
where father,left_son and right_son are the values of indices of the array.
Code –
135
Chapter 15. Binary Tree (Array implementation)
{
int t = (root * 2) + 2;
if(str[root] == null){
System.out.printf("Can't set child at %d, no parent found\n",t);
}else{
str[t] = key;
}
}
public void print_Tree()
{
for (int i = 0; i < 10; i++) {
if (str[i] != null)
System.out.print(str[i]);
else
System.out.print("-");
}
}
}
Output:
Note – Please refer this if you want to construct tree from the given parent array.
Improved By : Sachin Jain 1
Source
https://www.geeksforgeeks.org/binary-tree-array-implementation/
136
Chapter 16
Example 1
Input:
10
/ \
2 7
/ \
8 4
Output:
8
/ \
4 10
/ \
2 7
Example 2
Input:
10
/ \
30 15
/ \
20 5
137
Chapter 16. Binary Tree to Binary Search Tree Conversion
Output:
15
/ \
10 20
/ \
5 30
Solution
Following is a 3 step solution for converting Binary tree to Binary Search Tree.
1) Create a temp array arr[] that stores inorder traversal of the tree. This step takes O(n)
time.
2) Sort the temp array arr[]. Time complexity of this step depends upon the sorting algo-
rithm. In the following implementation, Quick Sort is used which takes (n^2) time. This
can be done in O(nLogn) time using Heap Sort or Merge Sort.
3) Again do inorder traversal of tree and copy array elements to tree nodes one by one. This
step takes O(n) time.
Following is C implementation of the above approach. The main function to convert is
highlighted in the following code.
C
138
Chapter 16. Binary Tree to Binary Search Tree Conversion
139
Chapter 16. Binary Tree to Binary Search Tree Conversion
140
Chapter 16. Binary Tree to Binary Search Tree Conversion
/* Constructing tree given in the above figure
10
/ \
30 15
/ \
20 5 */
root = newNode(10);
root->left = newNode(30);
root->right = newNode(15);
root->left->left = newNode(20);
root->right->right = newNode(5);
// convert Binary Tree to BST
binaryTreeToBST (root);
printf("Following is Inorder Traversal of the converted BST: \n");
printInorder (root);
return 0;
}
Python
141
Chapter 16. Binary Tree to Binary Search Tree Conversion
142
Chapter 16. Binary Tree to Binary Search Tree Conversion
arrayToBST(arr, root)
# Print the inorder traversal of the tree
def printInorder(root):
if root is None:
return
printInorder(root.left)
print root.data,
printInorder(root.right)
# Driver program to test above function
root = Node(10)
root.left = Node(30)
root.right = Node(15)
root.left.left = Node(20)
root.right.right= Node(5)
# Convert binary tree to BST
binaryTreeToBST(root)
print "Following is the inorder traversal of the converted BST"
printInorder(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
We will be covering another method for this problem which converts the tree using O(height
of tree) extra space.
Source
https://www.geeksforgeeks.org/binary-tree-to-binary-search-tree-conversion/
143
Chapter 17
Binary Tree to Binary Search Tree Conversion using STL set - GeeksforGeeks
Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in
such a way that keeps the original structure of Binary Tree.
This solution will use Sets of C++ STL instead of array based solution.
Examples:
Example 1
Input:
10
/ \
2 7
/ \
8 4
Output:
8
/ \
4 10
/ \
2 7
Example 2
Input:
10
/ \
30 15
/ \
144
Chapter 17. Binary Tree to Binary Search Tree Conversion using STL set
20 5
Output:
15
/ \
10 20
/ \
5 30
Solution
1. Copy the items of binary tree in a set while doing inorder traversal. This takes O(n
log n) time. Note that set in C++ STL is implemented using a Self Balancing Binary
Search Tree like Red Black Tree, AVL Tree, etc
2. There is no need to sort the set as sets in C++ are implemented using Self-balancing
binary search trees due to which each operation such as insertion, searching, deletion
etc takes O(log n) time.
3. Now simply copy the items of set one by one from beginning to the tree while doing
inorder traversal of tree. Care should be taken as when copying each item of set from
its beginning, we first copy it to the tree while doing inorder traversal, then remove it
from the set as well.
Now the above solution is simpler and easier to implement than the array based conversion
of Binary tree to Binary search tree explained here- Conversion of Binary Tree to Binary
Search tree (Set-1), where we had to separately make a function to sort the items of the
array after copying the items from tree to it.
C++ program to convert a binary tree to binary search tree using set.
145
Chapter 17. Binary Tree to Binary Search Tree Conversion using STL set
// insertion takes order of O(logn) for sets
s.insert(root->data);
// visit the right subtree
storeinorderInSet(root->right, s);
} // Time complexity = O(nlogn)
// function to copy items of set one by one
// to the tree while doing inorder traversal
void setToBST(set<int>& s, Node* root)
{
// base condition
if (!root)
return;
// first move to the left subtree and
// update items
setToBST(s, root->left);
// iterator initially pointing to the
// beginning of set
auto it = s.begin();
// copying the item at beginning of
// set(sorted) to the tree.
root->data = *it;
// now erasing the beginning item from set.
s.erase(it);
// now move to right subtree and update items
setToBST(s, root->right);
} // T(n) = O(nlogn) time
// Converts Binary tree to BST.
void binaryTreeToBST(Node* root)
{
set<int> s;
// populating the set with the tree's
// inorder traversal data
storeinorderInSet(root, s);
// now sets are by default sorted as
// they are implemented using self-
146
Chapter 17. Binary Tree to Binary Search Tree Conversion using STL set
147
Chapter 17. Binary Tree to Binary Search Tree Conversion using STL set
Output:
Source
https://www.geeksforgeeks.org/binary-tree-binary-search-tree-conversion-using-stl-set/
148
Chapter 18
tree
----
j <-- root
/ \
f k
/ \ \
a h z <-- leaves
Why Trees?
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:
file system
-----------
/ <-- root
/ \
... home
149
Chapter 18. Binary Tree | Set 1 (Introduction)
/ \
ugrad course
/ / | \
... cs101 cs112 cs113
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 Un-
ordered Linked Lists).
4. Like Linked Lists and unlike Arrays, Trees don’t have an upper limit on number of nodes
as nodes are linked using pointers.
Main applications of trees include:
1. Manipulate hierarchical data.
2. Make information easy to search (see tree traversal).
3. Manipulate sorted lists of data.
4. As a workflow for compositing digital images for visual effects.
5. Router algorithms
6. Form of a multi-stage decision-making (see business chess).
Binary Tree: A tree whose elements have at most 2 children is called a binary tree. Since
each element in a binary tree can have only 2 children, we typically name them the left and
right child.
Binary Tree Representation in C: A tree is represented by a pointer to the topmost
node in tree. If the tree is empty, then value of root is NULL.
A Tree node contains following parts.
1. Data
2. Pointer to left child
3. Pointer to right child
In C, we can represent a tree node using structures. Below is an example of a tree node
with an integer data.
C
struct node
{
int data;
struct node *left;
struct node *right;
};
Python
150
Chapter 18. Binary Tree | Set 1 (Introduction)
self.right = None
self.val = key
Java
tree
----
1 <-- root
/ \
2 3
/
4
struct node
{
int data;
struct node *left;
struct node *right;
};
/* newNode() allocates a new node with the given data and NULL left and
right pointers. */
struct node* newNode(int data)
{
// Allocate memory for new node
struct node* node = (struct node*)malloc(sizeof(struct node));
151
Chapter 18. Binary Tree | Set 1 (Introduction)
// Assign data to this node
node->data = data;
// Initialize left and right children as NULL
node->left = NULL;
node->right = NULL;
return(node);
}
int main()
{
/*create root*/
struct node *root = newNode(1);
/* following is the tree after above statement
1
/ \
NULL NULL
*/
root->left = newNode(2);
root->right = newNode(3);
/* 2 and 3 become left and right children of 1
1
/ \
2 3
/ \ / \
NULL NULL NULL NULL
*/
root->left->left = newNode(4);
/* 4 becomes left child of 2
1
/ \
2 3
/ \ / \
4 NULL NULL NULL
/ \
NULL NULL
*/
getchar();
return 0;
}
152
Chapter 18. Binary Tree | Set 1 (Introduction)
Python
Java
153
Chapter 18. Binary Tree | Set 1 (Introduction)
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
// A Java program to introduce Binary Tree
class BinaryTree
{
// Root of Binary Tree
Node root;
// Constructors
BinaryTree(int key)
{
root = new Node(key);
}
BinaryTree()
{
root = null;
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
/*create root*/
tree.root = new Node(1);
/* following is the tree after above statement
1
/ \
null null */
tree.root.left = new Node(2);
tree.root.right = new Node(3);
/* 2 and 3 become left and right children of 1
1
/ \
2 3
/ \ / \
154
Chapter 18. Binary Tree | Set 1 (Introduction)
Summary: Tree is a hierarchical data structure. Main uses of trees include maintaining
hierarchical data, providing moderate access and insert/delete operations. Binary trees are
special cases of tree where every node has at most two children.
Below are set 2 and set 3 of this post.
Properties of Binary Tree
Types of Binary Tree
Improved By : nsp92
Source
https://www.geeksforgeeks.org/binary-tree-set-1-introduction/
155
Chapter 19
156
Chapter 19. Binary Tree | Set 2 (Properties)
A Binary tree has maximum number of leaves (and minimum number of levels) when all
levels are fully filled. Let all leaves be at level l, then below is true for number of leaves L.
5) In Binary tree where every node has 0 or 2 children, number of leaf nodes
is always one more than nodes with two children.
L = T + 1
Where L = Number of leaf nodes
T = Number of internal nodes with two children
Source
https://www.geeksforgeeks.org/binary-tree-set-2-properties/
157
Chapter 20
18
/ \
15 30
/ \ / \
40 50 100 40
18
/ \
15 20
/ \
40 50
/ \
30 50
18
/ \
40 30
/ \
100 40
158
Chapter 20. Binary Tree | Set 3 (Types of Binary Tree)
18
/ \
15 30
/ \ / \
40 50 100 40
18
/ \
15 30
/ \ / \
40 50 100 40
/ \ /
8 7 9
18
/ \
15 30
/ \ / \
40 50 100 40
18
/ \
15 30
A Perfect Binary Tree of height h (where height is number of nodes on path from root to
leaf) has 2h – 1 node.
Example of Perfect binary tree is ancestors in family. Keep a person at root, parents as
children, parents of parents as their children.
159
Chapter 20. Binary Tree | Set 3 (Types of Binary Tree)
10
/
20
\
30
\
40
Source:
https://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees
Source
https://www.geeksforgeeks.org/binary-tree-set-3-types-of-binary-tree/
160
Chapter 21
161
Chapter 21. Binary tree to string with brackets
This is opposite of Construct Binary Tree from String with bracket representation
The idea is to do the preorder traversal of the given Binary Tree along with this, we need
to make use of braces at appropriate positions. But, we also need to make sure that we
omit the unnecessary braces. We print the current node and call the same given function
for the left and the right children of the node in that order(if they exist). For every node
encountered, the following cases are possible.
Case 1: Both the left child and the right child exist for the current node. In this case,
we need to put the braces () around both the left child’s preorder traversal output and the
right child’s preorder traversal output.
Case 2: None of the left or the right child exist for the current node. In this case, as
shown in the figure below, considering empty braces for the null left and right children is
redundant. Hence, we need not put braces for any of them.
Case 3: Only the left child exists for the current node. As the figure below shows, putting
empty braces for the right child in this case is unnecessary while considering the preorder
traversal. This is because the right child will always come after the left child in the preorder
traversal. Thus, omitting the empty braces for the right child also leads to same mapping
between the string and the binary tree.
162
Chapter 21. Binary tree to string with brackets
Case 4: Only the right child exists for the current node. In this case, we need to consider
the empty braces for the left child. This is because, during the preorder traversal, the left
child needs to be considered first. Thus, to indicate that the child following the current
node is a right child we need to put a pair of empty braces for the left child.
163
Chapter 21. Binary tree to string with brackets
164
Chapter 21. Binary tree to string with brackets
root->right->right = newNode(6);
string str = "";
treeToString(root, str);
cout << str;
}
Output:
1(2(4)(5))(3()(6))
Time complexity : O(n) The preorder traversal is done over the n nodes.
Space complexity : O(n). The depth of the recursion tree can go upto n in case of a
skewed tree.
Source
https://www.geeksforgeeks.org/binary-tree-string-brackets/
165
Chapter 22
20
/ \
8 22
/ \ \
5 3 25
/ \
10 14
For the above tree the output should be 5, 10, 3, 14, 25.
If there are multiple bottom-most nodes for a horizontal distance from root, then print
the later one in level traversal. For example, in the below diagram, 3 and 4 are both the
bottom-most nodes at horizontal distance 0, we need to print 4.
20
/ \
8 22
/ \ / \
5 3 4 25
/ \
10 14
166
Chapter 22. Bottom View of a Binary Tree
For the above tree the output should be 5, 10, 4, 14, 25.
Source
https://www.geeksforgeeks.org/bottom-view-binary-tree/
C++
167
Chapter 22. Bottom View of a Binary Tree
168
Chapter 22. Bottom View of a Binary Tree
temp->right->hd = hd+1;
q.push(temp->right);
}
}
// Traverse the map elements using the iterator.
for (auto i = m.begin(); i != m.end(); ++i)
cout << i->second << " ";
}
// Driver Code
int main()
{
Node *root = new Node(20);
root->left = new Node(8);
root->right = new Node(22);
root->left->left = new Node(5);
root->left->right = new Node(3);
root->right->left = new Node(4);
root->right->right = new Node(25);
root->left->right->left = new Node(10);
root->left->right->right = new Node(14);
cout << "Bottom view of the given binary tree :\n"
bottomView(root);
return 0;
}
Java
169
Chapter 22. Bottom View of a Binary Tree
//Tree class
class Tree
{
Node root; //root node of tree
// Default constructor
public Tree() {}
// Parameterized tree constructor
public Tree(Node node)
{
root = node;
}
// Method that prints the bottom view.
public void bottomView()
{
if (root == null)
return;
// Initialize a variable 'hd' with 0 for the root element.
int hd = 0;
// TreeMap which stores key value pair sorted on key value
Map<Integer, Integer> map = new TreeMap<>();
// Queue to store tree nodes in level order traversal
Queue<Node> queue = new LinkedList<Node>();
// Assign initialized horizontal distance value to root
// node and add it to the queue.
root.hd = hd;
queue.add(root);
// Loop until the queue is empty (standard level order loop)
while (!queue.isEmpty())
{
Node temp = queue.remove();
// Extract the horizontal distance value from the
// dequeued tree node.
hd = temp.hd;
// Put the dequeued tree node to TreeMap having key
// as horizontal distance. Every time we find a node
// having same horizontal distance we need to replace
// the data in the map.
170
Chapter 22. Bottom View of a Binary Tree
map.put(hd, temp.data);
// If the dequeued node has a left child add it to the
// queue with a horizontal distance hd-1.
if (temp.left != null)
{
temp.left.hd = hd-1;
queue.add(temp.left);
}
// If the dequeued node has a left child add it to the
// queue with a horizontal distance hd+1.
if (temp.right != null)
{
temp.right.hd = hd+1;
queue.add(temp.right);
}
}
// Extract the entries of map into a set to traverse
// an iterator over that.
Set<Entry<Integer, Integer>> set = map.entrySet();
// Make an iterator
Iterator<Entry<Integer, Integer>> iterator = set.iterator();
// Traverse the map elements using the iterator.
while (iterator.hasNext())
{
Map.Entry<Integer, Integer> me = iterator.next();
System.out.print(me.getValue()+" ");
}
}
}
// Main driver class
public class BottomView
{
public static void main(String[] args)
{
Node root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(5);
root.left.right = new Node(3);
root.right.left = new Node(4);
root.right.right = new Node(25);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
171
Chapter 22. Bottom View of a Binary Tree
Output:
C++
172
Chapter 22. Bottom View of a Binary Tree
}
};
void printBottomViewUtil(Node * root, int curr, int hd, map <int, pair <int, int>> & m)
{
// Base case
if (root == NULL)
return;
// If node for a particular
// horizontal distance is not
// present, add to the map.
if (m.find(hd) == m.end())
{
m[hd] = make_pair(root -> data, curr);
}
// Compare height for already
// present node at similar horizontal
// distance
else
{
pair < int, int > p = m[hd];
if (p.second <= curr)
{
m[hd].second = curr;
m[hd].first = root -> data;
}
}
// Recur for left subtree
printBottomViewUtil(root -> left, curr + 1, hd - 1, m);
// Recur for right subtree
printBottomViewUtil(root -> right, curr + 1, hd + 1, m);
}
void printBottomView(Node * root)
{
// Map to store Horizontal Distance,
// Height and Data.
map < int, pair < int, int > > m;
printBottomViewUtil(root, 0, 0, m);
// Prints the values stored by printBottomViewUtil()
map < int, pair < int, int > > ::iterator it;
for (it = m.begin(); it != m.end(); ++it)
173
Chapter 22. Bottom View of a Binary Tree
{
pair < int, int > p = it -> second;
cout << p.first << " ";
}
}
int main()
{
Node * root = new Node(20);
root -> left = new Node(8);
root -> right = new Node(22);
root -> left -> left = new Node(5);
root -> left -> right = new Node(3);
root -> right -> left = new Node(4);
root -> right -> right = new Node(25);
root -> left -> right -> left = new Node(10);
root -> left -> right -> right = new Node(14);
cout << "Bottom view of the given binary tree :\n";
printBottomView(root);
return 0;
}
174
Chapter 23
175
Chapter 23. Boundary Traversal of binary tree
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node *left, *right;
};
// A simple function to print leaf nodes of a binary tree
void printLeaves(struct node* root)
{
if ( root )
{
printLeaves(root->left);
// Print it if it is a leaf node
if ( !(root->left) && !(root->right) )
printf("%d ", root->data);
printLeaves(root->right);
}
}
// A function to print all left boundry nodes, except a leaf node.
// Print the nodes in TOP DOWN manner
void printBoundaryLeft(struct node* root)
{
if (root)
{
if (root->left)
{
// to ensure top down order, print the node
// before calling itself for left subtree
printf("%d ", root->data);
printBoundaryLeft(root->left);
}
else if( root->right )
{
printf("%d ", root->data);
printBoundaryLeft(root->right);
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}
176
Chapter 23. Boundary Traversal of binary tree
// A function to print all right boundry nodes, except a leaf node
// Print the nodes in BOTTOM UP manner
void printBoundaryRight(struct node* root)
{
if (root)
{
if ( root->right )
{
// to ensure bottom up order, first call for right
// subtree, then print this node
printBoundaryRight(root->right);
printf("%d ", root->data);
}
else if ( root->left )
{
printBoundaryRight(root->left);
printf("%d ", root->data);
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}
// A function to do boundary traversal of a given binary tree
void printBoundary (struct node* root)
{
if (root)
{
printf("%d ",root->data);
// Print the left boundary in top-down manner.
printBoundaryLeft(root->left);
// Print all leaf nodes
printLeaves(root->left);
printLeaves(root->right);
// Print the right boundary in bottom-up manner
printBoundaryRight(root->right);
}
}
// A utility function to create a node
struct node* newNode( int data )
{
struct node* temp = (struct node *) malloc( sizeof(struct node) );
177
Chapter 23. Boundary Traversal of binary tree
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us construct the tree given in the above diagram
struct node *root = newNode(20);
root->left = newNode(8);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
root->right = newNode(22);
root->right->right = newNode(25);
printBoundary( root );
return 0;
}
Java
178
Chapter 23. Boundary Traversal of binary tree
179
Chapter 23. Boundary Traversal of binary tree
printBoundaryRight(node.right);
System.out.print(node.data + " ");
}
else if (node.left != null)
{
printBoundaryRight(node.left);
System.out.print(node.data + " ");
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}
// A function to do boundary traversal of a given binary tree
void printBoundary(Node node)
{
if (node != null)
{
System.out.print(node.data + " ");
// Print the left boundary in top-down manner.
printBoundaryLeft(node.left);
// Print all leaf nodes
printLeaves(node.left);
printLeaves(node.right);
// Print the right boundary in bottom-up manner
printBoundaryRight(node.right);
}
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(20);
tree.root.left = new Node(8);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(12);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(14);
tree.root.right = new Node(22);
tree.root.right.right = new Node(25);
tree.printBoundary(tree.root);
}
}
180
Chapter 23. Boundary Traversal of binary tree
// This code has been contributed by Mayank Jaiswal(mayank_24)
Python
181
Chapter 23. Boundary Traversal of binary tree
Output:
182
Chapter 23. Boundary Traversal of binary tree
20 8 4 10 14 25 22
Source
https://www.geeksforgeeks.org/boundary-traversal-of-binary-tree/
183
Chapter 24
The given tree can be seen as a full binary tree where every node has 0 or two children. The
two children of a node can ‘n’ or ‘l’ or mix of both.
Examples :
Input : nlnll
Output : 2
Explanation :
Input : nlnnlll
Output : 3
184
Chapter 24. Calculate depth of a full Binary tree from Preorder
C++
185
Chapter 24. Calculate depth of a full Binary tree from Preorder
Java
186
Chapter 24. Calculate depth of a full Binary tree from Preorder
C#
187
Chapter 24. Calculate depth of a full Binary tree from Preorder
Console.WriteLine(findDepth(tree, n));
}
}
// This code is contributed by vt_m.
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/calculate-depth-full-binary-tree-preorder/
188
Chapter 25
Expalnation: First we should calculate value count[s] : the number of nodes in subtree
of node s. Where subtree contains the node itself and all the nodes in the subtree of its
189
Chapter 25. Calculate number of nodes in all subtrees | Using DFS
children. Thus, we can calculate the number of nodes recursively using concept of DFS and
DP, where we should process each edge only once and count[] value of a children used in
calculating count[] of its parent expressing the concept of DP(Dynamic programming).
Time Complexity : O(n) [in processing of all (n-1) edges].
Algorithm :
void numberOfNodes(int s, int e)
{
vector::iterator u;
count1[s] = 1;
for (u = adj[s].begin(); u != adj[s].end(); u++)
{
// condition to omit reverse path
// path from children to parent
if (*u == e)
continue;
C++
190
Chapter 25. Calculate number of nodes in all subtrees | Using DFS
191
Chapter 25. Calculate number of nodes in all subtrees | Using DFS
printNumberOfNodes();
return 0;
}
Java
192
Chapter 25. Calculate number of nodes in all subtrees | Using DFS
{
for (int i = 1; i < N; i++)
System.out.println("Node of a subtree of "+ i+
" : "+ count1[i]);
}
// Driver function
public static void main(String[] args)
{
// Creating list for all nodes
for(int i = 0; i < N; i++)
adj[i] = new ArrayList<>();
// insertion of nodes in graph
addEdge(1, 2);
addEdge(1, 4);
addEdge(1, 5);
addEdge(2, 6);
addEdge(4, 3);
addEdge(4, 7);
// call to perform dfs calculation
// making 1 as root of tree
numberOfNodes(1, 0);
// print result
printNumberOfNodes();
}
}
// This code is contributed by Sumit Ghosh
Output:
Nodes in subtree of 1: 7
Nodes in subtree of 2: 2
Nodes in subtree of 3: 1
Nodes in subtree of 4: 3
Nodes in subtree of 5: 1
Nodes in subtree of 6: 1
Nodes in subtree of 7: 1
193
Chapter 25. Calculate number of nodes in all subtrees | Using DFS
Source
https://www.geeksforgeeks.org/calculate-number-nodes-subtrees-using-dfs/
194
Chapter 26
Change a Binary Tree so that every node stores sum of all nodes in left subtree - Geeks-
forGeeks
Given a Binary Tree, change the value in each node to sum of all the values in the nodes in
the left subtree including its own.
Example
Input :
1
/ \
2 3
Output :
3
/ \
2 3
Input
1
/ \
2 3
/ \ \
4 5 6
Output:
12
195
Chapter 26. Change a Binary Tree so that every node stores sum of all nodes in left
subtree
/ \
6 3
/ \ \
4 5 6
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to traverse the given tree in bottom up manner. For every node, recursively
compute sum of nodes in left and right subtrees. Add sum of nodes in left subtree to current
node and return sum of nodes under current subtree.
Below is C++ implementation of above idea.
196
Chapter 26. Change a Binary Tree so that every node stores sum of all nodes in left
subtree
Output:
197
Chapter 26. Change a Binary Tree so that every node stores sum of all nodes in left
subtree
Source
https://www.geeksforgeeks.org/change-a-binary-tree-so-that-every-node-stores-sum-of-all-nodes-in-left-subtree/
198
Chapter 27
Algorithm:
Traverse the given binary tree. For each node check (recursively) if the node and both its
children satisfy the Children Sum Property, if so then return true else return false.
Implementation:
199
Chapter 27. Check for Children Sum Property in a Binary Tree
/* A binary tree node has data, left child and right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* returns 1 if children sum property holds for the given
node and both of its children*/
int isSumProperty(struct node* node)
{
/* left_data is left child data and right_data is for right
child data*/
int left_data = 0, right_data = 0;
/* If node is NULL or it's a leaf node then
return true */
if(node == NULL ||
(node->left == NULL && node->right == NULL))
return 1;
else
{
/* If left child is not present then 0 is used
as data of left child */
if(node->left != NULL)
left_data = node->left->data;
/* If right child is not present then 0 is used
as data of right child */
if(node->right != NULL)
right_data = node->right->data;
/* if the node and both of its children satisfy the
property return 1 else 0*/
if((node->data == left_data + right_data)&&
isSumProperty(node->left) &&
isSumProperty(node->right))
return 1;
else
return 0;
}
}
/*
Helper function that allocates a new node
with the given data and NULL left and right
pointers.
200
Chapter 27. Check for Children Sum Property in a Binary Tree
*/
struct node* newNode(int data)
{
struct node* node =
(struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above function */
int main()
{
struct node *root = newNode(10);
root->left = newNode(8);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->right = newNode(2);
if(isSumProperty(root))
printf("The given tree satisfies the children sum property ");
else
printf("The given tree does not satisfy the children sum property ");
getchar();
return 0;
}
Java
201
Chapter 27. Check for Children Sum Property in a Binary Tree
{
Node root;
/* returns 1 if children sum property holds for the given
node and both of its children*/
int isSumProperty(Node node)
{
/* left_data is left child data and right_data is for right
child data*/
int left_data = 0, right_data = 0;
/* If node is NULL or it's a leaf node then
return true */
if (node == null
|| (node.left == null && node.right == null))
return 1;
else
{
/* If left child is not present then 0 is used
as data of left child */
if (node.left != null)
left_data = node.left.data;
/* If right child is not present then 0 is used
as data of right child */
if (node.right != null)
right_data = node.right.data;
/* if the node and both of its children satisfy the
property return 1 else 0*/
if ((node.data == left_data + right_data)
&& (isSumProperty(node.left)!=0)
&& isSumProperty(node.right)!=0)
return 1;
else
return 0;
}
}
/* driver program to test the above functions */
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(8);
tree.root.right = new Node(2);
202
Chapter 27. Check for Children Sum Property in a Binary Tree
Output:
Source
https://www.geeksforgeeks.org/check-for-children-sum-property-in-a-binary-tree/
203
Chapter 28
Input :
1
/ \
2 2
/ \ / \
3 4 4 3
Output : Symmetric
Input :
1
/ \
2 2
\ \
3 3
204
Chapter 28. Check for Symmetric Binary Tree (Iterative Approach)
In this post, iterative approach is discussed. We use Queue here. Note that for a symmetric
that elements at every level are palindromic. In example 2, at the leaf level- the elements
are which is not palindromic.
In other words,
1. The left child of left subtree = right child of right subtree.
2. The right child of left subtree = left child of right subtree.
If we insert the left child of left subtree first followed by right child of the right subtree in
the queue, we only need to ensure that these are equal.
Similarly, If we insert the right child of left subtree followed by left child of the right subtree
in the queue, we again need to ensure that these are equal.
Below is the implementation based on above idea.
C++
205
Chapter 28. Check for Symmetric Binary Tree (Iterative Approach)
// Add root to queue two times so that
// it can be checked if either one child
// alone is NULL or not.
q.push(root);
q.push(root);
// To store two nodes for checking their
// symmetry.
Node* leftNode, *rightNode;
while(!q.empty()){
// Remove first two nodes to check
// their symmetry.
leftNode = q.front();
q.pop();
rightNode = q.front();
q.pop();
// if both left and right nodes
// exist, but have different
// values--> inequality, return false
if(leftNode->key != rightNode->key){
return false;
}
// Push left child of left subtree node
// and right child of right subtree
// node in queue.
if(leftNode->left && rightNode->right){
q.push(leftNode->left);
q.push(rightNode->right);
}
// If only one child is present alone
// and other is NULL, then tree
// is not symmetric.
else if (leftNode->left || rightNode->right)
return false;
// Push right child of left subtree node
// and left child of right subtree node
// in queue.
if(leftNode->right && rightNode->left){
q.push(leftNode->right);
q.push(rightNode->left);
206
Chapter 28. Check for Symmetric Binary Tree (Iterative Approach)
}
// If only one child is present alone
// and other is NULL, then tree
// is not symmetric.
else if(leftNode->right || rightNode->left)
return false;
}
return true;
}
// Driver program
int main()
{
// Let us construct the Tree shown in
// the above figure
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(4);
root->right->right = newNode(3);
if(isSymmetric(root))
cout << "The given tree is Symmetric";
else
cout << "The given tree is not Symmetric";
return 0;
}
// This code is contributed by Nikhil jindal.
Java
207
Chapter 28. Check for Symmetric Binary Tree (Iterative Approach)
{
val = v;
left = null;
right = null;
}
}
/* constructor to initialise the root */
BinaryTree(Node r) { root = r; }
/* empty constructor */
BinaryTree() { }
/* function to check if the tree is Symmetric */
public boolean isSymmetric(Node root)
{
/* This allows adding null elements to the queue */
Queue<Node> q = new LinkedList<Node>();
/* Initially, add left and right nodes of root */
q.add(root.left);
q.add(root.right);
while (!q.isEmpty())
{
/* remove the front 2 nodes to
check for equality */
Node tempLeft = q.remove();
Node tempRight = q.remove();
/* if both are null, continue and chcek
for further elements */
if (tempLeft==null && tempRight==null)
continue;
/* if only one is null---inequality, retun false */
if ((tempLeft==null && tempRight!=null) ||
(tempLeft!=null && tempRight==null))
return false;
/* if both left and right nodes exist, but
have different values-- inequality,
return false*/
if (tempLeft.val != tempRight.val)
return 0;
/* Note the order of insertion of elements
208
Chapter 28. Check for Symmetric Binary Tree (Iterative Approach)
Improved By : nik1996
Source
https://www.geeksforgeeks.org/check-symmetric-binary-tree-iterative-approach/
209
Chapter 29
Check given array of size n can represent BST of n levels or not - GeeksforGeeks
Given an array of size n, the task is to find whether array can represent a BST with n levels.
Since levels are n, we construct a tree in the following manner.
Assuming a number X,
Explanation :
210
Chapter 29. Check given array of size n can represent BST of n levels or not
For the sequence 500, 200, 90, 250, 100 formed tree(in above image) can’t represent BST.
The sequence 5123, 3300, 783, 1111, 890 forms a binary search tree hence its a correct
sequence.
Method 1 : By constructing BST
We first insert all array values level by level in a Tree. To insert, we check if current value is
less than previous value or greater. After constructing the tree, we check if the constructed
tree is Binary Search Tree or not.
211
Chapter 29. Check given array of size n can represent BST of n levels or not
Node* newNode(int num)
{
Node* temp = new Node;
temp->key = num;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// To create a Tree with n levels. We always
// insert new node to left if it is less than
// previous value.
Node* createNLevelTree(int arr[], int n)
{
Node* root = newNode(arr[0]);
Node* temp = root;
for (int i = 1; i < n; i++) {
if (temp->key > arr[i]) {
temp->left = newNode(arr[i]);
temp = temp->left;
}
else {
temp->right = newNode(arr[i]);
temp = temp->right;
}
}
return root;
}
// Please refer below post for details of this
// function.
// https:// www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/
bool isBST(Node* root, int min, int max)
{
if (root == NULL)
return true;
if (root->key < min || root->key > max)
return false;
// Allow only distinct values
return (isBST(root->left, min,
(root->key) - 1)
&& isBST(root->right,
(root->key) + 1, max));
}
212
Chapter 29. Check given array of size n can represent BST of n levels or not
Output:
Yes
213
Chapter 29. Check given array of size n can represent BST of n levels or not
Output:
Yes
Source
https://www.geeksforgeeks.org/check-given-array-of-size-n-can-represent-bst-of-n-levels-or-not/
214
Chapter 30
A simple solution is to store inorder traversal of given binary tree in an array. Then check
if array has duplicates or not. We can avoid the use of array and solve the problem in O(n)
time. The idea is to use hashing. We traverse the given tree, for every node, we check if it
already exists in hash table. If exists, we return true (found duplicate). If it does not exist,
we insert into hash table.
215
Chapter 30. Check if a Binary Tree (not BST) has duplicate values
C++
216
Chapter 30. Check if a Binary Tree (not BST) has duplicate values
Output:
Yes
Source
https://www.geeksforgeeks.org/check-binary-tree-not-bst-duplicate-values/
217
Chapter 31
218
Chapter 31. Check if a Binary Tree contains duplicate subtrees of size 2 or more
219
Chapter 31. Check if a Binary Tree contains duplicate subtrees of size 2 or more
220
Chapter 31. Check if a Binary Tree contains duplicate subtrees of size 2 or more
{
Node *root = newNode('A');
root->left = newNode('B');
root->right = newNode('C');
root->left->left = newNode('D');
root->left->right = newNode('E');
root->right->right = newNode('B');
root->right->right->right = newNode('E');
root->right->right->left= newNode('D');
string str = dupSubUtil(root);
(str.compare("") == 0) ? cout << " Yes ":
cout << " No " ;
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/check-binary-tree-contains-duplicate-subtrees-size-2/
221
Chapter 32
Input : 1
/ \
/ \
2 3
/ \ / \
/ \ / \
4 5 6 7
Output : Sorted
Input: 1
/
4
/ \
6 5
\
2
Output: Not sorted
Simple Solution: A simple solution is to compare minimum and maximum value of each
adjacent level i and i+1. Traverse to ith and i+1th level, compare the minimum value of
i+1th level with maximum value of ith level and return the result.
Time complexity: O(n2 ).
222
Chapter 32. Check if a binary tree is sorted level-wise or not
Efficient Solution: An efficient solution is to do level order traversal and keep track of
the minimum and maximum values of current level. Use a variable prevMax to store the
maximum value of the previous level. Then compare the minimum value of current level
with the maximum value of the previous level, pevMax. If minimum value is greater than the
prevMax, then the given tree is sorted level-wise up to current level. For next level, prevMax
is the equal to maximum value of current level. So update the prevMax with maximum
value of current level. Repeat this until all levels of given tree are not traversed.
Below is the implementation of above approach:
223
Chapter 32. Check if a binary tree is sorted level-wise or not
224
Chapter 32. Check if a binary tree is sorted level-wise or not
return 1;
}
// Driver program
int main()
{
/*
1
/
4
\
6
/ \
8 9
/ \
12 10
*/
Node* root = newNode(1);
root->left = newNode(4);
root->left->right = newNode(6);
root->left->right->left = newNode(8);
root->left->right->right = newNode(9);
root->left->right->left->left = newNode(12);
root->left->right->right->right = newNode(10);
if (isSorted(root))
cout << "Sorted";
else
cout << "Not sorted";
return 0;
}
Output:
Sorted
Source
https://www.geeksforgeeks.org/check-if-a-binary-tree-is-sorted-level-wise-or-not/
225
Chapter 33
Tree 2
10
/ \
4 6
\
30
Tree 1
26
/ \
10 3
/ \ \
4 6 3
\
30
226
Chapter 33. Check if a binary tree is subtree of another binary tree | Set 1
Solution: Traverse the tree T in preorder fashion. For every visited node in the traversal,
see if the subtree rooted with this node is identical to S.
Following is the implementation for this.
C
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, left child and right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* A utility function to check whether trees with roots as root1 and
root2 are identical or not */
bool areIdentical(struct node * root1, struct node *root2)
{
/* base cases */
if (root1 == NULL && root2 == NULL)
return true;
if (root1 == NULL || root2 == NULL)
return false;
/* Check if the data of both roots is same and data of left and right
subtrees are also same */
return (root1->data == root2->data &&
areIdentical(root1->left, root2->left) &&
areIdentical(root1->right, root2->right) );
}
/* This function returns true if S is a subtree of T, otherwise false */
bool isSubtree(struct node *T, struct node *S)
{
/* base cases */
if (S == NULL)
return true;
if (T == NULL)
return false;
/* Check the tree with root as current node */
if (areIdentical(T, S))
227
Chapter 33. Check if a binary tree is subtree of another binary tree | Set 1
return true;
/* If the tree with root as current node doesn't match then
try left and right subtrees one by one */
return isSubtree(T->left, S) ||
isSubtree(T->right, S);
}
/* Helper function that allocates a new node with the given data
and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node =
(struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above function */
int main()
{
// TREE 1
/* Construct the following tree
26
/ \
10 3
/ \ \
4 6 3
\
30
*/
struct node *T = newNode(26);
T->right = newNode(3);
T->right->right = newNode(3);
T->left = newNode(10);
T->left->left = newNode(4);
T->left->left->right = newNode(30);
T->left->right = newNode(6);
// TREE 2
/* Construct the following tree
10
/ \
4 6
\
228
Chapter 33. Check if a binary tree is subtree of another binary tree | Set 1
30
*/
struct node *S = newNode(10);
S->right = newNode(6);
S->left = newNode(4);
S->left->right = newNode(30);
if (isSubtree(T, S))
printf("Tree 2 is subtree of Tree 1");
else
printf("Tree 2 is not a subtree of Tree 1");
getchar();
return 0;
}
Java
229
Chapter 33. Check if a binary tree is subtree of another binary tree | Set 1
return false;
/* Check if the data of both roots is same and data of left and right
subtrees are also same */
return (root1.data == root2.data
&& areIdentical(root1.left, root2.left)
&& areIdentical(root1.right, root2.right));
}
/* This function returns true if S is a subtree of T, otherwise false */
boolean isSubtree(Node T, Node S)
{
/* base cases */
if (S == null)
return true;
if (T == null)
return false;
/* Check the tree with root as current node */
if (areIdentical(T, S))
return true;
/* If the tree with root as current node doesn't match then
try left and right subtrees one by one */
return isSubtree(T.left, S)
|| isSubtree(T.right, S);
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
// TREE 1
/* Construct the following tree
26
/ \
10 3
/ \ \
4 6 3
\
30 */
tree.root1 = new Node(26);
tree.root1.right = new Node(3);
tree.root1.right.right = new Node(3);
tree.root1.left = new Node(10);
tree.root1.left.left = new Node(4);
230
Chapter 33. Check if a binary tree is subtree of another binary tree | Set 1
Python
231
Chapter 33. Check if a binary tree is subtree of another binary tree | Set 1
# Check fi the data of both roots is same and data of
# left and right subtrees are also same
return (root1.data == root2.data and
areIdentical(root1.left , root2.left)and
areIdentical(root1.right, root2.right)
)
# This function returns True if S is a subtree of T,
# otherwise False
def isSubtree(T, S):
# Base Case
if S is None:
return True
if T is None:
return False
# Check the tree with root as current node
if (areIdentical(T, S)):
return True
# IF the tree with root as current node doesn't match
# then try left and right subtreee one by one
return isSubtree(T.left, S) or isSubtree(T.right, S)
# Driver program to test above function
""" TREE 1
Construct the following tree
26
/ \
10 3
/ \ \
4 6 3
\
30
"""
T = Node(26)
T.right = Node(3)
T.right.right = Node(3)
T.left = Node(10)
T.left.left = Node(4)
T.left.left.right = Node(30)
T.left.right = Node(6)
232
Chapter 33. Check if a binary tree is subtree of another binary tree | Set 1
""" TREE 2
Construct the following tree
10
/ \
4 6
\
30
"""
S = Node(10)
S.right = Node(6)
S.left = Node(4)
S.left.right = Node(30)
if isSubtree(T, S):
print "Tree 2 is subtree of Tree 1"
else :
print "Tree 2 is not a subtree of Tree 1"
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time Complexity: Time worst case complexity of above solution is O(mn) where m and n
are number of nodes in given two trees.
We can solve the above problem in O(n) time. Please refer Check if a binary tree is subtree
of another binary tree | Set 2 for O(n) solution.
Improved By : SrivathsanAravamudan
Source
https://www.geeksforgeeks.org/check-if-a-binary-tree-is-subtree-of-another-binary-tree/
233
Chapter 34
Tree1
x
/ \
a b
\
c
Tree2
z
/ \
x e
/ \ \
a b k
\
c
We have discussed a O(n2 ) solution for this problem. In this post a O(n) solution is discussed.
The idea is based on the fact that inorder and preorder/postorder uniquely identify a binary
234
Chapter 34. Check if a binary tree is subtree of another binary tree | Set 2
tree. Tree S is a subtree of T if both inorder and preorder traversals of S arew substrings of
inorder and preorder traversals of T respectively.
Following are detailed steps.
1) Find inorder and preorder traversals of T, store them in two auxiliary arrays inT[] and
preT[].
2) Find inorder and preorder traversals of S, store them in two auxiliary arrays inS[] and
preS[].
3) If inS[] is a subarray of inT[] and preS[] is a subarray preT[], then S is a subtree of T.
Else not.
We can also use postorder traversal in place of preorder in the above algorithm.
Let us consider the above example
EDIT
The above algorithm doesn't work for cases where a tree is present
in another tree, but not as a subtree. Consider the following example.
Tree1
x
/ \
a b
/
c
Tree2
x
/ \
a b
/ \
c d
235
Chapter 34. Check if a binary tree is subtree of another binary tree | Set 2
The Tree2 is not a subtree of Tree1, but inS[] and preS[] are
subarrays of inT[] and preT[] respectively.
The above algorithm can be extended to handle such cases by adding a special character
whenever we encounter NULL in inorder and preorder traversals. Thanks to Shivam Goel
for suggesting this extension.
Following is the implementation of above algorithm.
C
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 100
// Structure of a tree node
struct Node
{
char key;
struct Node *left, *right;
};
// A utility function to create a new BST node
Node *newNode(char item)
{
Node *temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to store inorder traversal of tree rooted
// with root in an array arr[]. Note that i is passed as reference
void storeInorder(Node *root, char arr[], int &i)
{
if (root == NULL)
{
arr[i++] = '$';
return;
}
storeInorder(root->left, arr, i);
arr[i++] = root->key;
storeInorder(root->right, arr, i);
236
Chapter 34. Check if a binary tree is subtree of another binary tree | Set 2
}
// A utility function to store preorder traversal of tree rooted
// with root in an array arr[]. Note that i is passed as reference
void storePreOrder(Node *root, char arr[], int &i)
{
if (root == NULL)
{
arr[i++] = '$';
return;
}
arr[i++] = root->key;
storePreOrder(root->left, arr, i);
storePreOrder(root->right, arr, i);
}
/* This function returns true if S is a subtree of T, otherwise false */
bool isSubtree(Node *T, Node *S)
{
/* base cases */
if (S == NULL) return true;
if (T == NULL) return false;
// Store Inorder traversals of T and S in inT[0..m-1]
// and inS[0..n-1] respectively
int m = 0, n = 0;
char inT[MAX], inS[MAX];
storeInorder(T, inT, m);
storeInorder(S, inS, n);
inT[m] = '\0', inS[n] = '\0';
// If inS[] is not a substring of preS[], return false
if (strstr(inT, inS) == NULL)
return false;
// Store Preorder traversals of T and S in inT[0..m-1]
// and inS[0..n-1] respectively
m = 0, n = 0;
char preT[MAX], preS[MAX];
storePreOrder(T, preT, m);
storePreOrder(S, preS, n);
preT[m] = '\0', preS[n] = '\0';
// If inS[] is not a substring of preS[], return false
// Else return true
return (strstr(preT, preS) != NULL);
}
237
Chapter 34. Check if a binary tree is subtree of another binary tree | Set 2
Java
238
Chapter 34. Check if a binary tree is subtree of another binary tree | Set 2
239
Chapter 34. Check if a binary tree is subtree of another binary tree | Set 2
240
Chapter 34. Check if a binary tree is subtree of another binary tree | Set 2
Output:
Time Complexity: Inorder and Preorder traversals of Binary Tree take O(n) time. The func-
tion strstr() can also be implemented in O(n) time using KMP string matching algorithm.
Auxiliary Space: O(n)
Thanks to Ashwini Singh for suggesting this method. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/check-binary-tree-subtree-another-binary-tree-set-2/
241
Chapter 35
1. It should be a complete tree (i.e. all levels except last should be full).
2. Every node’s value should be greater than or equal to its child node (considering
max-heap).
242
Chapter 35. Check if a given Binary Tree is Heap
We check each of the above condition separately, for checking completeness isComplete and
for checking heap isHeapUtil function are written.
Detail about isComplete function can be found here.
isHeapUtil function is written considering following things –
1. Every Node can have 2 children, 0 child (last level nodes) or 1 child (there can be at
most one such node).
2. If Node has No child then it’s a leaf node and return true (Base case)
3. If Node has one child (it must be left child because it is a complete tree) then we need
to compare this node with its single child only.
4. If Node has both child then check heap property at Node at recur for both subtrees.
Complete code.
Implementation
C/C++
243
Chapter 35. Check if a given Binary Tree is Heap
244
Chapter 35. Check if a given Binary Tree is Heap
else
{
// Check heap property at Node and
// Recursive check heap property at left and right subtree
if (root->key >= root->left->key &&
root->key >= root->right->key)
return ((isHeapUtil(root->left)) &&
(isHeapUtil(root->right)));
else
return (false);
}
}
// Function to check binary tree is a Heap or Not.
bool isHeap(struct Node* root)
{
// These two are used in isCompleteUtil()
unsigned int node_count = countNodes(root);
unsigned int index = 0;
if (isCompleteUtil(root, index, node_count) && isHeapUtil(root))
return true;
return false;
}
// Driver program
int main()
{
struct Node* root = NULL;
root = newNode(10);
root->left = newNode(9);
root->right = newNode(8);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
root->left->left->left = newNode(3);
root->left->left->right = newNode(2);
root->left->right->left = newNode(1);
if (isHeap(root))
printf("Given binary tree is a Heap\n");
else
printf("Given binary tree is not a Heap\n");
return 0;
}
245
Chapter 35. Check if a given Binary Tree is Heap
Java
246
Chapter 35. Check if a given Binary Tree is Heap
247
Chapter 35. Check if a given Binary Tree is Heap
Python
248
Chapter 35. Check if a given Binary Tree is Heap
Output:
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : scorncer17
Source
https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-heap/
249
Chapter 36
26
/ \
10 3
/ \ \
4 6 3
Method 1 ( Simple )
Get the sum of nodes in left subtree and right subtree. Check if the sum calculated is equal
to root’s data. Also, recursively check if the left and right subtrees are SumTrees.
C
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, left child and right child */
struct node
{
int data;
struct node* left;
250
Chapter 36. Check if a given Binary Tree is SumTree
251
Chapter 36. Check if a given Binary Tree is SumTree
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above function */
int main()
{
struct node *root = newNode(26);
root->left = newNode(10);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(6);
root->right->right = newNode(3);
if(isSumTree(root))
printf("The given tree is a SumTree ");
else
printf("The given tree is not a SumTree ");
getchar();
return 0;
}
Java
252
Chapter 36. Check if a given Binary Tree is SumTree
253
Chapter 36. Check if a given Binary Tree is SumTree
Output:
Time Complexity: O(n^2) in worst case. Worst case occurs for a skewed tree.
Method 2 ( Tricky )
The Method 1 uses sum() to get the sum of nodes in left and right subtrees. The method 2
uses following rules to get the sum directly.
1) If the node is a leaf node then sum of subtree rooted with this node is equal to value of
this node.
2) If the node is not a leaf node then sum of subtree rooted with this node is twice the value
of this node (Assuming that the tree rooted with this node is SumTree).
C
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, left child and right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Utillity function to check if the given node is leaf or not */
int isLeaf(struct node *node)
{
if(node == NULL)
return 0;
if(node->left == NULL && node->right == NULL)
return 1;
return 0;
}
/* returns 1 if SumTree property holds for the given
tree */
int isSumTree(struct node* node)
{
int ls; // for sum of nodes in left subtree
int rs; // for sum of nodes in right subtree
/* If node is NULL or it's a leaf node then
return true */
if(node == NULL || isLeaf(node))
254
Chapter 36. Check if a given Binary Tree is SumTree
return 1;
if( isSumTree(node->left) && isSumTree(node->right))
{
// Get the sum of nodes in left subtree
if(node->left == NULL)
ls = 0;
else if(isLeaf(node->left))
ls = node->left->data;
else
ls = 2*(node->left->data);
// Get the sum of nodes in right subtree
if(node->right == NULL)
rs = 0;
else if(isLeaf(node->right))
rs = node->right->data;
else
rs = 2*(node->right->data);
/* If root's data is equal to sum of nodes in left
and right subtrees then return 1 else return 0*/
return(node->data == ls + rs);
}
return 0;
}
/* Helper function that allocates a new node
with the given data and NULL left and right
pointers.
*/
struct node* newNode(int data)
{
struct node* node =
(struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above function */
int main()
{
struct node *root = newNode(26);
root->left = newNode(10);
root->right = newNode(3);
255
Chapter 36. Check if a given Binary Tree is SumTree
root->left->left = newNode(4);
root->left->right = newNode(6);
root->right->right = newNode(3);
if(isSumTree(root))
printf("The given tree is a SumTree ");
else
printf("The given tree is not a SumTree ");
getchar();
return 0;
}
Java
256
Chapter 36. Check if a given Binary Tree is SumTree
257
Chapter 36. Check if a given Binary Tree is SumTree
if (tree.isSumTree(tree.root) != 0)
System.out.println("The given tree is a sum tree");
else
System.out.println("The given tree is not a sum tree");
}
}
// This code has been contributed by Mayank Jaiswal
Output:
Source
https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree/
258
Chapter 37
Check if a given Binary Tree is height balanced like a Red-Black Tree - GeeksforGeeks
In a Red-Black Tree, the maximum height of a node is at most twice the minimum height
(The four Red-Black tree properties make sure this is always followed). Given a Binary
Search Tree, we need to check for following property.
For every node, length of the longest leaf to node path has not more than twice the nodes on
shortest path from node to leaf.
12 40
\ / \
14 10 100
\ / \
16 60 150
Cannot be a Red-Black Tree It can be Red-Black Tree
with any color assignment
Max height of 12 is 1
Min height of 12 is 3
10
/ \
5 100
/ \
50 150
/
40
259
Chapter 37. Check if a given Binary Tree is height balanced like a Red-Black Tree
Expected time complexity is O(n). The tree should be traversed at-most once in the solution.
We strongly recommend to minimize the browser and try this yourself first.
For every node, we need to get the maximum and minimum heights and compare them. The
idea is to traverse the tree and for every node check if it’s balanced. We need to write a
recursive function that returns three things, a boolean value to indicate the tree is balanced
or not, minimum height and maximum height. To return multiple values, we can either use
a structure or pass variables by reference. We have passed maxh and minh by reference so
that the values can be used in parent calls.
260
Chapter 37. Check if a given Binary Tree is height balanced like a Red-Black Tree
return false;
// Check if right subtree is balanced, also set rmxh and rmnh
if (isBalancedUtil(root->right, rmxh, rmnh) == false)
return false;
// Set the max and min heights of this node for the parent call
maxh = max(lmxh, rmxh) + 1;
minh = min(lmnh, rmnh) + 1;
// See if this node is balanced
if (maxh <= 2*minh)
return true;
return false;
}
// A wrapper over isBalancedUtil()
bool isBalanced(Node *root)
{
int maxh, minh;
return isBalancedUtil(root, maxh, minh);
}
/* Driver program to test above functions*/
int main()
{
Node * root = newNode(10);
root->left = newNode(5);
root->right = newNode(100);
root->right->left = newNode(50);
root->right->right = newNode(150);
root->right->left->left = newNode(40);
isBalanced(root)? cout << "Balanced" : cout << "Not Balanced";
return 0;
}
Output:
Balanced
Time Complexity: Time Complexity of above code is O(n) as the code does a simple tree
traversal.
Source
https://www.geeksforgeeks.org/check-given-binary-tree-follows-height-property-red-black-tree/
261
Chapter 38
Check if a given array can represent Preorder Traversal of Binary Search Tree - Geeks-
forGeeks
Given an array of numbers, return true if given array can represent preorder traversal of a
Binary Search Tree, else return false. Expected time complexity is O(n).
Examples:
4
/
3
262
Chapter 38. Check if a given array can represent Preorder Traversal of Binary Search Tree
40
/
30 80
35 100
A Simple Solution is to do following for every node pre[i] starting from first one.
263
Chapter 38. Check if a given array can represent Preorder Traversal of Binary Search Tree
264
Chapter 38. Check if a given array can represent Preorder Traversal of Binary Search Tree
Java
265
Chapter 38. Check if a given array can represent Preorder Traversal of Binary Search Tree
public static void main(String args[]) {
BinarySearchTree bst = new BinarySearchTree();
int[] pre1 = new int[]{40, 30, 35, 80, 100};
int n = pre1.length;
if (bst.canRepresentBST(pre1, n) == true) {
System.out.println("true");
} else {
System.out.println("false");
}
int[] pre2 = new int[]{40, 30, 35, 20, 80, 100};
int n1 = pre2.length;
if (bst.canRepresentBST(pre2, n) == true) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
//This code is contributed by Mayank Jaiswal
Python
266
Chapter 38. Check if a given array can represent Preorder Traversal of Binary Search Tree
Output:
true
false
This article is contributed by Romil Punetha. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/check-if-a-given-array-can-represent-preorder-traversal-of-binary-search-tree/
267
Chapter 39
268
Chapter 39. Check if a given graph is tree or not
For an undirected graph we can either use BFSor DFSto detect above two properties.
How to detect cycle in an undirected graph?
We can either use BFS or DFS. For every visited vertex ‘v’, if there is an adjacent ‘u’ such
that u is already visited and u is not parent of v, then there is a cycle in graph. If we don’t
find such an adjacent for any vertex, we say that there is no cycle (SeeDetect cycle in an
undirected graph for more details).
How to check for connectivity?
Since the graph is undirected, we can start BFS or DFS from any vertex and check if all
vertices are reachable or not. If all vertices are reachable, then graph is connected, otherwise
not.
C++
269
Chapter 39. Check if a given graph is tree or not
270
Chapter 39. Check if a given graph is tree or not
Java
271
Chapter 39. Check if a given graph is tree or not
adj[v].add(w);
adj[w].add(v);
}
// A recursive function that uses visited[] and parent
// to detect cycle in subgraph reachable from vertex v.
Boolean isCyclicUtil(int v, Boolean visited[], int parent)
{
// Mark the current node as visited
visited[v] = true;
Integer i;
// Recur for all the vertices adjacent to this vertex
Iterator<Integer> it = adj[v].iterator();
while (it.hasNext())
{
i = it.next();
// If an adjacent is not visited, then recur for
// that adjacent
if (!visited[i])
{
if (isCyclicUtil(i, visited, v))
return true;
}
// If an adjacent is visited and not parent of
// current vertex, then there is a cycle.
else if (i != parent)
return true;
}
return false;
}
// Returns true if the graph is a tree, else false.
Boolean isTree()
{
// Mark all the vertices as not visited and not part
// of recursion stack
Boolean visited[] = new Boolean[V];
for (int i = 0; i < V; i++)
visited[i] = false;
// The call to isCyclicUtil serves multiple purposes
// It returns true if graph reachable from vertex 0
// is cyclcic. It also marks all vertices reachable
// from 0.
if (isCyclicUtil(0, visited, -1))
272
Chapter 39. Check if a given graph is tree or not
return false;
// If we find a vertex which is not reachable from 0
// (not marked by isCyclicUtil(), then we return false
for (int u = 0; u < V; u++)
if (!visited[u])
return false;
return true;
}
// Driver method
public static void main(String args[])
{
// Create a graph given in the above diagram
Graph g1 = new Graph(5);
g1.addEdge(1, 0);
g1.addEdge(0, 2);
g1.addEdge(0, 3);
g1.addEdge(3, 4);
if (g1.isTree())
System.out.println("Graph is Tree");
else
System.out.println("Graph is not Tree");
Graph g2 = new Graph(5);
g2.addEdge(1, 0);
g2.addEdge(0, 2);
g2.addEdge(2, 1);
g2.addEdge(0, 3);
g2.addEdge(3, 4);
if (g2.isTree())
System.out.println("Graph is Tree");
else
System.out.println("Graph is not Tree");
}
}
// This code is contributed by Aakash Hasija
Python
273
Chapter 39. Check if a given graph is tree or not
class Graph():
def __init__(self, V):
self.V = V
self.graph = defaultdict(list)
def addEdge(self, v, w):
# Add w to v ist.
self.graph[v].append(w)
# Add v to w list.
self.graph[w].append(v)
# A recursive function that uses visited[]
# and parent to detect cycle in subgraph
# reachable from vertex v.
def isCyclicUtil(self, v, visited, parent):
# Mark current node as visited
visited[v] = True
# Recur for all the vertices adjacent
# for this vertex
for i in self.graph[v]:
# If an adjacent is not visited,
# then recur for that adjacent
if visited[i] == False:
if self.isCyclicUtil(i, visited, v) == True:
return True
# If an adjacent is visited and not
# parent of current vertex, then there
# is a cycle.
elif i != parent:
return True
return False
# Returns true if the graph is a tree,
# else false.
def isTree(self):
# Mark all the vertices as not visited
# and not part of recursion stack
visited = [False] * self.V
# The call to isCyclicUtil serves multiple
# purposes. It returns true if graph reachable
# from vertex 0 is cyclcic. It also marks
# all vertices reachable from 0.
274
Chapter 39. Check if a given graph is tree or not
Output:
Graph is Tree
Graph is not Tree
Thanks to Vinit Verma for suggesting this problem and initial solution. Please write
comments if you find anything incorrect, or you want to share more information about the
topic discussed above
Source
https://www.geeksforgeeks.org/check-given-graph-tree/
275
Chapter 40
12
/ \
5 7
/ \
3 1
Leaves are at same level
12
/ \
5 7
/
3
Leaves are Not at same level
12
/
5
/ \
3 9
/ /
1 2
Leaves are at same level
Method 1 (Recursive)
276
Chapter 40. Check if all leaves are at same level
The idea is to first find level of the leftmost leaf and store it in a variable leafLevel. Then
compare level of all other leaves with leafLevel, if same, return true, else return false. We
traverse the given Binary Tree in Preorder fashion. An argument leaflevel is passed to all
calls. The value of leafLevel is initialized as 0 to indicate that the first leaf is not yet seen
yet. The value is updated when we find first leaf. Level of subsequent leaves (in preorder)
is compared with leafLevel.
C
277
Chapter 40. Check if all leaves are at same level
// If this node is not leaf, recursively check left and right subtrees
return checkUtil(root->left, level+1, leafLevel) &&
checkUtil(root->right, level+1, leafLevel);
}
/* The main function to check if all leafs are at same level.
It mainly uses checkUtil() */
bool check(struct Node *root)
{
int level = 0, leafLevel = 0;
return checkUtil(root, level, &leafLevel);
}
// Driver program to test above function
int main()
{
// Let us create tree shown in thirdt example
struct Node *root = newNode(12);
root->left = newNode(5);
root->left->left = newNode(3);
root->left->right = newNode(9);
root->left->left->left = newNode(1);
root->left->right->left = newNode(1);
if (check(root))
printf("Leaves are at same level\n");
else
printf("Leaves are not at same level\n");
getchar();
return 0;
}
Java
278
Chapter 40. Check if all leaves are at same level
class Leaf
{
int leaflevel=0;
}
class BinaryTree
{
Node root;
Leaf mylevel = new Leaf();
/* Recursive function which checks whether all leaves are at same
level */
boolean checkUtil(Node node, int level, Leaf leafLevel)
{
// Base case
if (node == null)
return true;
// If a leaf node is encountered
if (node.left == null && node.right == null)
{
// When a leaf node is found first time
if (leafLevel.leaflevel == 0)
{
// Set first found leaf's level
leafLevel.leaflevel = level;
return true;
}
// If this is not first leaf node, compare its level with
// first leaf's level
return (level == leafLevel.leaflevel);
}
// If this node is not leaf, recursively check left and right
// subtrees
return checkUtil(node.left, level + 1, leafLevel)
&& checkUtil(node.right, level + 1, leafLevel);
}
/* The main function to check if all leafs are at same level.
It mainly uses checkUtil() */
boolean check(Node node)
{
int level = 0;
return checkUtil(node, level, mylevel);
}
279
Chapter 40. Check if all leaves are at same level
public static void main(String args[])
{
// Let us create the tree as shown in the example
BinaryTree tree = new BinaryTree();
tree.root = new Node(12);
tree.root.left = new Node(5);
tree.root.left.left = new Node(3);
tree.root.left.right = new Node(9);
tree.root.left.left.left = new Node(1);
tree.root.left.right.left = new Node(1);
if (tree.check(tree.root))
System.out.println("Leaves are at same level");
else
System.out.println("Leaves are not at same level");
}
}
// This code has been contributed by Mayank Jaiswal
Python
280
Chapter 40. Check if all leaves are at same level
# If this is not first leaf node, compare its level
# with first leaf's level
return level == check.leafLevel
# If this is not first leaf node, compare its level
# with first leaf's level
return (checkUtil(root.left, level+1)and
checkUtil(root.right, level+1))
def check(root):
level = 0
check.leafLevel = 0
return (checkUtil(root, level))
# Driver program to test above function
root = Node(12)
root.left = Node(5)
root.left.left = Node(3)
root.left.right = Node(9)
root.left.left.left = Node(1)
root.left.right.left = Node(2)
if(check(root)):
print "Leaves are at same level"
else:
print "Leaves are not at same level"
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time Complexity: The function does a simple traversal of the tree, so the complexity is
O(n).
Method 1 (Iterative)
It can also be solved by iterative approach.
The idea is to iteratively traverse the tree, and when you encounter the first leaf node, store
it’s level in result variable, now whenever you encounter any leaf node, compare it’s level
with previously stored result, it they are same then proceed for rest of the tree, else return
false.
281
Chapter 40. Check if all leaves are at same level
282
Chapter 40. Check if all leaves are at same level
283
Chapter 40. Check if all leaves are at same level
root->right->right = newNode(6);
int result = checkLevelLeafNode(root);
if (result)
cout << "All leaf nodes are at same level\n";
else
cout << "Leaf nodes not at same level\n";
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/check-leaves-level/
284
Chapter 41
Tree 1:
Level 0 : 1
Level 1 : 3, 2
Level 2 : 5, 4
Tree 2:
Level 0 : 1
Level 1 : 2, 3
Level 2 : 4, 5
As we can clearly see all the levels of above two binary trees are anagrams of each other,
hence return true.
Naive Approach: Below is the step by step explanation of the naive approach to do this:
285
Chapter 41. Check if all levels of two trees are anagrams or not
C++
286
Chapter 41. Check if all levels of two trees are anagrams or not
287
Chapter 41. Check if all levels of two trees are anagrams or not
Java
288
Chapter 41. Check if all levels of two trees are anagrams or not
left = null;
right = null;
}
}
// Returns true if trees with root1 and root2
// are level by level anagram, else returns false.
static boolean areAnagrams(Node root1, Node root2)
{
// Base Cases
if (root1 == null && root2 == null)
return true;
if (root1 == null || root2 == null)
return false;
// start level order traversal of two trees
// using two queues.
Queue<Node> q1 = new LinkedList<Node>();
Queue<Node> q2 = new LinkedList<Node>();
q1.add(root1);
q2.add(root2);
while (true)
{
// n1 (queue size) indicates number of
// Nodes at current level in first tree
// and n2 indicates number of nodes in
// current level of second tree.
int n1 = q1.size(), n2 = q2.size();
// If n1 and n2 are different
if (n1 != n2)
return false;
// If level order traversal is over
if (n1 == 0)
break;
// Dequeue all Nodes of current level and
// Enqueue all Nodes of next level
ArrayList<Integer> curr_level1 = new
ArrayList<>();
ArrayList<Integer> curr_level2 = new
ArrayList<>();
while (n1 > 0)
{
Node node1 = q1.peek();
q1.remove();
289
Chapter 41. Check if all levels of two trees are anagrams or not
290
Chapter 41. Check if all levels of two trees are anagrams or not
}
}
// This code is contributed by Sumit Ghosh
Output:
Yes
Note: In the above program we are comparing the vectors storing each level of a tree
directly using not equal to function ‘ != ‘ which compares the vectors first on the basis
of their size and then on the basis of their content, hence saving our work of iteratively
comparing the vectors.
Source
https://www.geeksforgeeks.org/check-if-all-levels-of-two-trees-are-anagrams-or-not/
291
Chapter 42
The idea is to use the fact that the inorder traversal of Binary Search Tree is sorted. So,
just check if given array is sorted or not.
292
Chapter 42. Check if an array represents Inorder of Binary Search tree or not
Output:
Yes
Source
https://www.geeksforgeeks.org/check-array-represents-inorder-binary-search-tree-not/
293
Chapter 43
Check if given Preorder, Inorder and Postorder traversals are of same tree - GeeksforGeeks
Given Preorder , Inorder and Postorder traversals of some tree. Write a program to check
if they all are of the same tree.
Examples:
The most basic approach to solve this problem will be to first construct a tree using two of the
three given traversals and then do the third traversal on this constructed tree and compare
it with the given traversal. If both of the traversals are same then print Yes otherwise print
294
Chapter 43. Check if given Preorder, Inorder and Postorder traversals are of same tree
No. Here, we use Inorder and Preorder traversals to construct the tree. We may also use
Inorder and Postorder traversal instead of Preorder traversal for tree construction. You may
refer to this post on how to construct tree from given Inorder and Preorder traversal. After
constructing the tree, we will obtain the Postorder traversal of this tree and compare it with
the given Postorder traversal.
Below is the C++ implementation of above approach:
295
Chapter 43. Check if given Preorder, Inorder and Postorder traversals are of same tree
{
static int preIndex = 0;
if(inStrt > inEnd)
return NULL;
/* Pick current node from Preorder traversal
using preIndex and increment preIndex */
Node *tNode = newNode(pre[preIndex++]);
/* If this node has no children then return */
if (inStrt == inEnd)
return tNode;
/* Else find the index of this node in
Inorder traversal */
int inIndex = search(in, inStrt, inEnd, tNode->data);
/* Using index in Inorder traversal,
construct left and right subtress */
tNode->left = buildTree(in, pre, inStrt, inIndex-1);
tNode->right = buildTree(in, pre, inIndex+1, inEnd);
return tNode;
}
/* function to compare Postorder traversal
on constructed tree and given Postorder */
int checkPostorder(Node* node, int postOrder[], int index)
{
if (node == NULL)
return index;
/* first recur on left child */
index = checkPostorder(node->left,postOrder,index);
/* now recur on right child */
index = checkPostorder(node->right,postOrder,index);
/* Compare if data at current index in
both Postorder traversals are same */
if (node->data == postOrder[index])
index++;
else
return -1;
return index;
}
296
Chapter 43. Check if given Preorder, Inorder and Postorder traversals are of same tree
// Driver program to test above functions
int main()
{
int inOrder[] = {4, 2, 5, 1, 3};
int preOrder[] = {1, 2, 4, 5, 3};
int postOrder[] = {4, 5, 2, 3, 1};
int len = sizeof(inOrder)/sizeof(inOrder[0]);
// build tree from given
// Inorder and Preorder traversals
Node *root = buildTree(inOrder, preOrder, 0, len - 1);
// compare postorder traversal on constructed
// tree with given Postorder traversal
int index = checkPostorder(root,postOrder,0);
// If both postorder traversals are same
if (index == len)
cout << "Yes";
else
cout << "No";
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/check-if-given-preorder-inorder-and-postorder-traversals-are-of-same-tree/
297
Chapter 44
0
/ \
5 8
\ / \
4 6 7
Output: same
Leaf order traversal of both trees is 4 6 7
298
Chapter 44. Check if leaf traversal of two Binary Trees is same?
8 9
1
/ \
4 3
\ / \
8 2 9
We strongly recommend you to minimize your browser and try this yourself
first.
A Simple Solution is traverse first tree and store leaves from left and right in an array.
Then traverse other tree and store leaves in another array. Finally compare two arrays. If
both arrays are same, then return true.
The above solution requires O(m+n) extra space where m and n are nodes in first and
second tree respectively.
How to check with O(h1 + h2) space?
The idea is use iterative traversal. Traverse both trees simultaneously, look for a leaf node
in both trees and compare the found leaves. All leaves must match.
Algorithm:
299
Chapter 44. Check if leaf traversal of two Binary Trees is same?
{
push right child to stack1
push left child to stack1
}
300
Chapter 44. Check if leaf traversal of two Binary Trees is same?
301
Chapter 44. Check if leaf traversal of two Binary Trees is same?
// If both are not null and data is not
// same return false
if (temp1!=null && temp2!=null)
{
if (temp1.data != temp2.data)
return false;
}
}
// If control reaches this point, all leaves
// are matched
return true;
}
// Driver program to test
public static void main(String[] args)
{
// Let us create trees in above example 1
Node root1 = new Node(1);
root1.left = new Node(2);
root1.right = new Node(3);
root1.left.left = new Node(4);
root1.right.left = new Node(6);
root1.right.right = new Node(7);
Node root2 = new Node(0);
root2.left = new Node(1);
root2.right = new Node(5);
root2.left.right = new Node(4);
root2.right.left = new Node(6);
root2.right.right = new Node(7);
if (isSame(root1, root2))
System.out.println("Same");
else
System.out.println("Not Same");
}
}
Output:
Same
This article is contributed by Kumar Gaurav. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
302
Chapter 44. Check if leaf traversal of two Binary Trees is same?
Source
https://www.geeksforgeeks.org/check-if-leaf-traversal-of-two-binary-trees-is-same/
303
Chapter 45
Check if removing an edge can divide a Binary Tree in two halves - GeeksforGeeks
Given a Binary Tree, find if there exist edge whose removal creates two trees of equal size.
Examples:
304
Chapter 45. Check if removing an edge can divide a Binary Tree in two halves
Method 1 (Simple)
First count number of nodes in whole tree. Let count of all nodes be n. Now traverse tree
and for every node, find size of subtree rooted with this node. Let the subtree size be s. If
n-s is equal to s, then return true, else false.
C++
305
Chapter 45. Check if removing an edge can divide a Binary Tree in two halves
// Check for root
if (count(root) == n-count(root))
return true;
// Check for rest of the nodes
return checkRec(root->left, n) ||
checkRec(root->right, n);
}
// This function mainly uses checkRec()
bool check(Node *root)
{
// Count total nodes in given tree
int n = count(root);
// Now recursively check all nodes
return checkRec(root, n);
}
// Driver code
int main()
{
struct Node* root = newNode(5);
root->left = newNode(1);
root->right = newNode(6);
root->left->left = newNode(3);
root->right->left = newNode(7);
root->right->right = newNode(4);
check(root)? printf("YES") : printf("NO");
return 0;
}
Java
306
Chapter 45. Check if removing an edge can divide a Binary Tree in two halves
307
Chapter 45. Check if removing an edge can divide a Binary Tree in two halves
Output :
YES
Time complexity of above solution is O(n2 ) where n is number of nodes in given Binary
Tree.
Method 2 (Efficient)
We can find the solution in O(n) time. The idea is to traverse tree in bottom up manner
and while traversing keep updating size and keep checking if there is a node that follows the
required property.
Below is C++ and implementation of above idea.
C++
308
Chapter 45. Check if removing an edge can divide a Binary Tree in two halves
temp->data = x;
temp->left = temp->right = NULL;
return temp;
};
// To calculate size of tree with given root
int count(Node* root)
{
if (root==NULL)
return 0;
return count(root->left) + count(root->right) + 1;
}
// This function returns size of tree rooted with given
// root. It also set "res" as true if there is an edge
// whose removal divides tree in two halves.
// n is size of tree
int checkRec(Node* root, int n, bool &res)
{
// Base case
if (root == NULL)
return 0;
// Compute sizes of left and right children
int c = checkRec(root->left, n, res) + 1 +
checkRec(root->right, n, res);
// If required property is true for current node
// set "res" as true
if (c == n-c)
res = true;
// Return size
return c;
}
// This function mainly uses checkRec()
bool check(Node *root)
{
// Count total nodes in given tree
int n = count(root);
// Initialize result and recursively check all nodes
bool res = false;
checkRec(root, n, res);
return res;
}
309
Chapter 45. Check if removing an edge can divide a Binary Tree in two halves
// Driver code
int main()
{
struct Node* root = newNode(5);
root->left = newNode(1);
root->right = newNode(6);
root->left->left = newNode(3);
root->right->left = newNode(7);
root->right->right = newNode(4);
check(root)? printf("YES") : printf("NO");
return 0;
}
Java
310
Chapter 45. Check if removing an edge can divide a Binary Tree in two halves
311
Chapter 45. Check if removing an edge can divide a Binary Tree in two halves
Output :
YES
This article is contributed by Asaad Akram. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/check-if-removing-an-edge-can-divide-a-binary-tree-in-two-halves/
312
Chapter 46
Check if the given array can represent Level Order Traversal of Binary Search Tree - Geeks-
forGeeks
Given an array of size n. The problem is to check whether the given array can represent
the level order traversal of a Binary Search Tree or not.
Examples:
The idea is to use a queue data structure. Every element of queue has a structure say
NodeDetails which stores details of a tree node. The details are node’s data, and two
313
Chapter 46. Check if the given array can represent Level Order Traversal of Binary Search
Tree
variables min and max where min stores the lower limit for the node values which can be
a part of the left subtree and max stores the upper limit for the node values which can be a
part of the right subtree for the specified node in NodeDetails structure variable. For the
1st array value arr[0], create a NodeDetails structure having arr[0] as node’s data and min
= INT_MIN and max = INT_MAX. Add this structure variable to the queue. This Node
will be the root of the tree. Move to 2nd element in arr[] and then perform the following
steps:
Finally, if all the elements of the array have been traversed then the array represents the
level order traversal of a BST, else NOT.
314
Chapter 46. Check if the given array can represent Level Order Traversal of Binary Search
Tree
return true;
// queue to store NodeDetails
queue<NodeDetails> q;
// index variable to access array elements
int i=0;
// node details for the
// root of the BST
NodeDetails newNode;
newNode.data = arr[i++];
newNode.min = INT_MIN;
newNode.max = INT_MAX;
q.push(newNode);
// until there are no more elements
// in arr[] or queue is not empty
while (i != n && !q.empty())
{
// extracting NodeDetails of a
// node from the queue
NodeDetails temp = q.front();
q.pop();
// check whether there are more elements
// in the arr[] and arr[i] can be left child
// of 'temp.data' or not
if (i < n && (arr[i] < temp.data &&
arr[i] > temp.min))
{
// Create NodeDetails for newNode
/// and add it to the queue
newNode.data = arr[i++];
newNode.min = temp.min;
newNode.max = temp.data;
q.push(newNode);
}
// check whether there are more elements
// in the arr[] and arr[i] can be right child
// of 'temp.data' or not
if (i < n && (arr[i] > temp.data &&
arr[i] < temp.max))
{
// Create NodeDetails for newNode
/// and add it to the queue
newNode.data = arr[i++];
315
Chapter 46. Check if the given array can represent Level Order Traversal of Binary Search
Tree
newNode.min = temp.data;
newNode.max = temp.max;
q.push(newNode);
}
}
// given array represents level
// order traversal of BST
if (i == n)
return true;
// given array do not represent
// level order traversal of BST
return false;
}
// Driver program to test above
int main()
{
int arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10};
int n = sizeof(arr) / sizeof(arr[0]);
if (levelOrderIsOfBST(arr, n))
cout << "Yes";
else
cout << "No";
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/check-given-array-can-represent-level-order-traversal-binary-search-tree/
316
Chapter 47
317
Chapter 47. Check if there is a root to leaf path with given sequence
Examples :
A simple solution for this problem is to find all root to leaf paths in given tree and for
each root to leaf path check that path and given sequence in array both are identical or not.
318
Chapter 47. Check if there is a root to leaf path with given sequence
An efficient solution for this problem is to traverse the tree once and while traversing
the tree we have to check that if path from root to current node is identical to the given
sequence of root to leaf path. Here is the algorithm :
Path Exists
Source
https://www.geeksforgeeks.org/check-root-leaf-path-given-sequence/
319
Chapter 48
6
/ \
3 5
/ \ / \
7 8 1 3
Say two node be 7 and 1, result is TRUE.
Say two nodes are 3 and 5, result is FALSE.
Say two nodes are 7 and 5, result is FALSE.
The idea is to find level of one of the nodes. Using the found level, check if ‘a’ and ‘b’ are
at this level. If ‘a’ and ‘b’ are at given level, then finally check if they are not children of
same parent.
Following is the implementation of the above approach.
C
320
Chapter 48. Check if two nodes are cousins in a Binary Tree
321
Chapter 48. Check if two nodes are cousins in a Binary Tree
//2. The two Nodes should not be siblings (means that they should
// not have the same parent Node).
if ((level(root,a,1) == level(root,b,1)) && !(isSibling(root,a,b)))
return 1;
else return 0;
}
// Driver Program to test above functions
int main()
{
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->right->right = newNode(15);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
struct Node *Node1,*Node2;
Node1 = root->left->left;
Node2 = root->right->right;
isCousin(root,Node1,Node2)? puts("Yes"): puts("No");
return 0;
}
Java
322
Chapter 48. Check if two nodes are cousins in a Binary Tree
323
Chapter 48. Check if two nodes are cousins in a Binary Tree
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.left.right.right = new Node(15);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.right.left.right = new Node(8);
Node Node1, Node2;
Node1 = tree.root.left.left;
Node2 = tree.root.right.right;
if (tree.isCousin(tree.root, Node1, Node2))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code has been contributed by Mayank Jaiswal
Python
324
Chapter 48. Check if two nodes are cousins in a Binary Tree
# Recursive function to find level of Node 'ptr' in
# a binary tree
def level(root, ptr, lev):
# Base Case
if root is None :
return 0
if root == ptr:
return lev
# Return level if Node is present in left subtree
l = level(root.left, ptr, lev+1)
if l != 0:
return l
# Else search in right subtree
return level(root.right, ptr, lev+1)
# Returns 1 if a and b are cousins, otherwise 0
def isCousin(root,a, b):
# 1. The two nodes should be on the same level in
# the binary tree
# The two nodes should not be siblings(means that
# they should not have the smae parent node
if ((level(root,a,1) == level(root, b, 1)) and
not (isSibling(root, a, b))):
return 1
else:
return 0
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.left.right.right = Node(15)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right = Node(8)
node1 = root.left.right
node2 = root.right.right
325
Chapter 48. Check if two nodes are cousins in a Binary Tree
print "Yes" if isCousin(root, node1, node2) == 1 else "No"
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Ouput:
Yes
Time Complexity of the above solution is O(n) as it does at most three traversals of binary
tree.
Check if two nodes are cousins in a Binary Tree | Set-2
This article is contributed by Ayush Srivastava. Please write comments if you find any-
thing incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/check-two-nodes-cousins-binary-tree/
326
Chapter 49
6
/ \
3 5
/ \ / \
7 8 1 3
Say two node be 7 and 1, result is TRUE.
Say two nodes are 3 and 5, result is FALSE.
Say two nodes are 7 and 5, result is FALSE.
A solution in Set-1 that finds whether given nodes are cousins or not by performing three
traversals of binary tree has been discussed. The problem can be solved by performing level
order traversal. The idea is to use a queue to perform level order traversal, in which each
queue element is a pair of node and parent of that node. For each node visited in level
order traversal, check if that node is either first given node or second given node. If any
node is found store parent of that node. While performing level order traversal, one level
is traversed at a time. If both nodes are found in given level, then their parent values are
compared to check if they are siblings or not. If one node is found in given level and another
is not found, then given nodes are not cousins.
Below is the implementation of above approach:
327
Chapter 49. Check if two nodes are cousins in a Binary Tree | Set-2
328
Chapter 49. Check if two nodes are cousins in a Binary Tree | Set-2
329
Chapter 49. Check if two nodes are cousins in a Binary Tree | Set-2
// If one node is found in current level
// and another is not found, then
// both nodes are not cousins.
if ((parA && !parB) || (parB && !parA)) {
return false;
}
}
return false;
}
// Driver Code
int main()
{
/*
1
/ \
2 3
/ \ / \
4 5 6 7
\ \
15 8
*/
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->right->right = newNode(15);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
struct Node *Node1, *Node2;
Node1 = root->left->left;
Node2 = root->right->right;
isCousin(root, Node1, Node2) ? puts("Yes") : puts("No");
return 0;
}
Output:
Yes
330
Chapter 49. Check if two nodes are cousins in a Binary Tree | Set-2
Source
https://www.geeksforgeeks.org/check-if-two-nodes-are-cousins-in-a-binary-tree-set-2/
331
Chapter 50
C++
332
Chapter 50. Check if two trees are Mirror
/* A binary tree node has data, pointer to
left child and a pointer to right child */
struct Node
{
int data;
Node* left, *right;
};
/* Given two trees, return true if they are
mirror of each other */
int areMirror(Node* a, Node* b)
{
/* Base case : Both empty */
if (a==NULL && b==NULL)
return true;
// If only one is empty
if (a==NULL || b == NULL)
return false;
/* Both non-empty, compare them recursively
Note that in recursive calls, we pass left
of one tree and right of other tree */
return a->data == b->data &&
areMirror(a->left, b->right) &&
areMirror(a->right, b->left);
}
/* Helper function that allocates a new node */
Node* newNode(int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return(node);
}
/* Driver program to test areMirror() */
int main()
{
Node *a = newNode(1);
Node *b = newNode(1);
a->left = newNode(2);
a->right = newNode(3);
a->left->left = newNode(4);
a->left->right = newNode(5);
333
Chapter 50. Check if two trees are Mirror
b->left = newNode(3);
b->right = newNode(2);
b->right->left = newNode(5);
b->right->right = newNode(4);
areMirror(a, b)? cout << "Yes" : cout << "No";
return 0;
}
Java
334
Chapter 50. Check if two trees are Mirror
Python3
335
Chapter 50. Check if two trees are Mirror
return True
# If only one is empty
if a is None or b is None:
return False
# Both non-empty, compare them
# recursively. Note that in
# recursive calls, we pass left
# of one tree and right of other tree
return (a.data == b.data and
areMirror(a.left, b.right) and
areMirror(a.right , b.left))
# Driver code
root1 = Node(1)
root2 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.left.right = Node(5)
root2.left = Node(3)
root2.right = Node(2)
root2.right.left = Node(5)
root2.right.right = Node(4)
if areMirror(root1, root2):
print ("Yes")
else:
print ("No")
# This code is contributed by AshishR
Output :
Yes
336
Chapter 50. Check if two trees are Mirror
Source
https://www.geeksforgeeks.org/check-if-two-trees-are-mirror/
337
Chapter 51
Approach :
Find the inorder traversal of both the Binary Trees, and check whether one traversal is
reverse of another or not. If they are reverse of each other then the trees are mirror of each
other, else not.
CPP
338
Chapter 51. Check if two trees are Mirror | Set 2
// mirror.
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node* left, *right;
};
// inorder traversal of Binary Tree
void inorder(Node *n, vector<int> &v)
{
if (n->left != NULL)
inorder(n->left, v);
v.push_back(n->data);
if (n->right != NULL)
inorder(n->right, v);
}
// Checking if binary tree is mirror
// of each other or not.
bool areMirror(Node* a, Node* b)
{
if (a == NULL && b == NULL)
return true;
if (a == NULL || b== NULL)
return false;
// Storing inorder traversals of both
// the trees.
vector<int> v1, v2;
inorder(a, v1);
inorder(b, v2);
if (v1.size() != v2.size())
return false;
// Comparing the two arrays, if they
// are reverse then return 1, else 0
for (int i=0, j=v2.size()-1; j >= 0;
i++, j--)
if (v1[i] != v2[j])
return false;
return true;
}
339
Chapter 51. Check if two trees are Mirror | Set 2
// Helper function to allocate a new node
Node* newNode(int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return(node);
}
// Driver code
int main()
{
Node *a = newNode(1);
Node *b = newNode(1);
a -> left = newNode(2);
a -> right = newNode(3);
a -> left -> left = newNode(4);
a -> left -> right = newNode(5);
b -> left = newNode(3);
b -> right = newNode(2);
b -> right -> left = newNode(5);
b -> right -> right = newNode(4);
areMirror(a, b)? cout << "Yes" : cout << "No";
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/check-two-trees-mirror-set-2/
340
Chapter 52
Check if two trees are mirror of each other using level order traversal - GeeksforGeeks
Given two binary trees, the task is to check whether the two binary trees is a mirror of each
other or not.
Mirror of a Binary Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with
left and right children of all non-leaf nodes interchanged.
341
Chapter 52. Check if two trees are mirror of each other using level order traversal
342
Chapter 52. Check if two trees are mirror of each other using level order traversal
343
Chapter 52. Check if two trees are mirror of each other using level order traversal
344
Chapter 52. Check if two trees are mirror of each other using level order traversal
1
/ \
2 3
/ \
4 5
*/
Node* root2 = newNode(1);
root2->left = newNode(2);
root2->right = newNode(3);
root2->left->left = newNode(4);
root2->left->right = newNode(5);
cout << areMirrors(root1, root2);
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/check-if-two-trees-are-mirror-of-each-other-using-level-order-traversal/
345
Chapter 53
In the above figure both of the trees, Tree1 and Tree2 are identical in structure. That is,
they have the same structure.
Note: This problem is different from Check if two trees are identical as here we need to
compare only the structures of the two trees and not the values at their nodes.
The idea is to traverse both trees simultaneously following the same paths and keep checking
if a node exists for both the trees or not.
Algorithm:
346
Chapter 53. Check if two trees have same structure
347
Chapter 53. Check if two trees have same structure
return
(
isSameStructure(a->left, b->left) &&
isSameStructure(a->right, b->right)
);
}
// 3. one empty, one not -> false
return 0;
}
// Driver code
int main()
{
Node *root1 = newNode(10);
Node *root2 = newNode(100);
root1->left = newNode(7);
root1->right = newNode(15);
root1->left->left = newNode(4);
root1->left->right = newNode(9);
root1->right->right = newNode(20);
root2->left = newNode(70);
root2->right = newNode(150);
root2->left->left = newNode(40);
root2->left->right = newNode(90);
root2->right->right = newNode(200);
if (isSameStructure(root1, root2))
printf("Both trees have same structure");
else
printf("Trees do not have same structure");
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/check-if-two-trees-have-same-structure/
348
Chapter 54
The idea is to use Queue and Stack to check if given N-ary tree are mirror of each other or
not.
Let first n-ary tree be t1 and second n-ary tree is t2. For each node in t1, make stack and
push its connected node in it. Now, for each node in t2, make queue and push its connected
node in it.
Now, for each corresponding node do following:
349
Chapter 54. Check mirror in n-ary tree
b = front of stack;
if (a != b)
return false;
pop element from stack and queue.
350
Chapter 54. Check mirror in n-ary tree
Output:
Yes
Reference: https://practice.geeksforgeeks.org/problems/check-mirror-in-n-ary-tree/0
Source
https://www.geeksforgeeks.org/check-mirror-n-ary-tree/
351
Chapter 55
We strongly recommend you to minimize your browser and try this yourself
first.
For calculating sum of Uncovered nodes we will follow below steps:
1) Start from root, go to left and keep going until left child is available, if not go to right
child and again follow same procedure until you reach a leaf node.
2) After step 1 sum of left boundary will be stored, now for right part again do the same
procedure but now keep going to right until right child is available, if not then go to left
child and follow same procedure until you reach a leaf node.
After above 2 steps sum of all Uncovered node will be stored, we can subtract it from total
sum and get sum of covered elements and check for equines of binary tree.
C++
352
Chapter 55. Check sum of Covered and Uncovered nodes of Binary Tree
353
Chapter 55. Check sum of Covered and Uncovered nodes of Binary Tree
{
/* If leaf node, then just return its key value */
if (t->left == NULL && t->right == NULL)
return t->key;
/* If right is available then go right otherwise go left */
if (t->right != NULL)
return t->key + uncoveredSumRight(t->right);
else
return t->key + uncoveredSumRight(t->left);
}
// Returns sum of uncovered elements
int uncoverSum(Node* t)
{
/* Initializing with 0 in case we don't have
left or right boundary */
int lb = 0, rb = 0;
if (t->left != NULL)
lb = uncoveredSumLeft(t->left);
if (t->right != NULL)
rb = uncoveredSumRight(t->right);
/* returning sum of root node, left boundry
and right boundry*/
return t->key + lb + rb;
}
// Returns true if sum of covered and uncovered elements
// is same.
bool isSumSame(Node *root)
{
// Sum of uncovered elements
int sumUC = uncoverSum(root);
// Sum of all elements
int sumT = sum(root);
// Check if sum of covered and uncovered is same
return (sumUC == (sumT - sumUC));
}
/* Helper function to print inorder traversal of
binary tree */
void inorder(Node* root)
{
if (root)
354
Chapter 55. Check sum of Covered and Uncovered nodes of Binary Tree
{
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
// Driver program to test above functions
int main()
{
// Making above given diagram's binary tree
Node* root = newNode(8);
root->left = newNode(3);
root->left->left = newNode(1);
root->left->right = newNode(6);
root->left->right->left = newNode(4);
root->left->right->right = newNode(7);
root->right = newNode(10);
root->right->right = newNode(14);
root->right->right->left = newNode(13);
if (isSumSame(root))
printf("Sum of covered and uncovered is same\n");
else
printf("Sum of covered and uncovered is not same\n");
}
Java
355
Chapter 55. Check sum of Covered and Uncovered nodes of Binary Tree
class BinaryTree
{
Node root;
/* Utility function to calculate sum of all node of tree */
int sum(Node t)
{
if (t == null)
return 0;
return t.key + sum(t.left) + sum(t.right);
}
/* Recursive function to calculate sum of left boundary
elements */
int uncoveredSumLeft(Node t)
{
/* If left node, then just return its key value */
if (t.left == null && t.right == null)
return t.key;
/* If left is available then go left otherwise go right */
if (t.left != null)
return t.key + uncoveredSumLeft(t.left);
else
return t.key + uncoveredSumLeft(t.right);
}
/* Recursive function to calculate sum of right boundary
elements */
int uncoveredSumRight(Node t)
{
/* If left node, then just return its key value */
if (t.left == null && t.right == null)
return t.key;
/* If right is available then go right otherwise go left */
if (t.right != null)
return t.key + uncoveredSumRight(t.right);
else
return t.key + uncoveredSumRight(t.left);
}
// Returns sum of uncovered elements
int uncoverSum(Node t)
{
/* Initializing with 0 in case we don't have
left or right boundary */
int lb = 0, rb = 0;
356
Chapter 55. Check sum of Covered and Uncovered nodes of Binary Tree
if (t.left != null)
lb = uncoveredSumLeft(t.left);
if (t.right != null)
rb = uncoveredSumRight(t.right);
/* returning sum of root node, left boundry
and right boundry*/
return t.key + lb + rb;
}
// Returns true if sum of covered and uncovered elements
// is same.
boolean isSumSame(Node root)
{
// Sum of uncovered elements
int sumUC = uncoverSum(root);
// Sum of all elements
int sumT = sum(root);
// Check if sum of covered and uncovered is same
return (sumUC == (sumT - sumUC));
}
/* Helper function to print inorder traversal of
binary tree */
void inorder(Node root)
{
if (root != null)
{
inorder(root.left);
System.out.print(root.key + " ");
inorder(root.right);
}
}
// Driver program to test above functions
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
// Making above given diagram's binary tree
tree.root = new Node(8);
tree.root.left = new Node(3);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(6);
357
Chapter 55. Check sum of Covered and Uncovered nodes of Binary Tree
Output :
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : MayankShorey
Source
https://www.geeksforgeeks.org/check-sum-covered-uncovered-nodes-binary-tree/
358
Chapter 56
Input : 8
/ \
5 9
/ \
2 7
/
1
Output : Yes
Explanation : Node "1" is the dead End because
after that we cant insert any element.
Input : 8
/ \
7 10
/ / \
2 9 13
Output : Yes
Explanation : We can't insert any element at
node 9.
359
Chapter 56. Check whether BST contains Dead End or not
If we take a closer look at problem, we can notice that we basically need to check if there is
leaf node with value x such that x+1 and x-1 exist in BST with exception of x = 1. For x
= 1, we can’t insert 0 as problem statement says BST contains positive integers only.
To implement above idea we first traverse whole BST and store all nodes in a hash_map.
We also store all leaves in a separate hash to avoid re-traversal of BST. Finally we check for
every leaf node x, if x-1 and x+1 are present in hash_map or not.
Below is C++ implementation of above idea .
360
Chapter 56. Check whether BST contains Dead End or not
361
Chapter 56. Check whether BST contains Dead End or not
Output:
Yes
Source
https://www.geeksforgeeks.org/check-whether-bst-contains-dead-end-not/
362
Chapter 57
Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution) - Geeks-
forGeeks
A complete binary tree is a binary tree whose all levels except the last level are completely
filled and all the leaves in the last level are all to the left side. More information about
complete binary trees can be found here.
For Example:-
Below tree is a Complete Binary Tree (All nodes till the second last nodes are filled and all
leaves are to the left side)
363
Chapter 57. Check whether a binary tree is a complete tree or not | Set 2 (Recursive
Solution)
The time complexity of the above algorithm is O(n). Following is the code for checking if a
binary tree is a complete binary tree.
C
364
Chapter 57. Check whether a binary tree is a complete tree or not | Set 2 (Recursive
Solution)
365
Chapter 57. Check whether a binary tree is a complete tree or not | Set 2 (Recursive
Solution)
Java
366
Chapter 57. Check whether a binary tree is a complete tree or not | Set 2 (Recursive
Solution)
{
BinaryTree tree = new BinaryTree();
// Le us create tree in the last diagram above
Node NewRoot = null;
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.right = new Node(5);
tree.root.left.left = new Node(4);
tree.root.right.right = new Node(6);
int node_count = tree.countNodes(tree.root);
int index = 0;
if (tree.isComplete(tree.root, index, node_count))
System.out.print("The binary tree is complete");
else
System.out.print("The binary tree is not complete");
}
}
// This code is contributed by Mayank Jaiswal
Python
367
Chapter 57. Check whether a binary tree is a complete tree or not | Set 2 (Recursive
Solution)
Output:
This article is contributed by Gaurav Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/check-whether-binary-tree-complete-not-set-2-recursive-solution/
368
Chapter 58
To check whether a binary tree is a full binary tree we need to test the following cases:-
1) If a binary tree node is NULL then it is a full binary tree.
2) If a binary tree node does have empty left and right sub-trees, then it is a full binary tree
by definition.
369
Chapter 58. Check whether a binary tree is a full binary tree or not
3) If a binary tree node has left and right sub-trees, then it is a part of a full binary tree by
definition. In this case recursively check if the left and right sub-trees are also binary trees
themselves.
4) In all other combinations of right and left sub-trees, the binary tree is not a full binary
tree.
Following is the implementation for checking if a binary tree is a full binary tree.
C
370
Chapter 58. Check whether a binary tree is a full binary tree or not
return false;
}
// Driver Program
int main()
{
struct Node* root = NULL;
root = newNode(10);
root->left = newNode(20);
root->right = newNode(30);
root->left->right = newNode(40);
root->left->left = newNode(50);
root->right->left = newNode(60);
root->right->right = newNode(70);
root->left->left->left = newNode(80);
root->left->left->right = newNode(90);
root->left->right->left = newNode(80);
root->left->right->right = newNode(90);
root->right->left->left = newNode(80);
root->right->left->right = newNode(90);
root->right->right->left = newNode(80);
root->right->right->right = newNode(90);
if (isFullTree(root))
printf("The Binary Tree is full\n");
else
printf("The Binary Tree is not full\n");
return(0);
}
Java
371
Chapter 58. Check whether a binary tree is a full binary tree or not
}
class BinaryTree
{
Node root;
/* this function checks if a binary tree is full or not */
boolean isFullTree(Node node)
{
// if empty tree
if(node == null)
return true;
// if leaf node
if(node.left == null && node.right == null )
return true;
// if both left and right subtrees are not null
// the are full
if((node.left!=null) && (node.right!=null))
return (isFullTree(node.left) && isFullTree(node.right));
// if none work
return false;
}
// Driver program
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(20);
tree.root.right = new Node(30);
tree.root.left.right = new Node(40);
tree.root.left.left = new Node(50);
tree.root.right.left = new Node(60);
tree.root.left.left.left = new Node(80);
tree.root.right.right = new Node(70);
tree.root.left.left.right = new Node(90);
tree.root.left.right.left = new Node(80);
tree.root.left.right.right = new Node(90);
tree.root.right.left.left = new Node(80);
tree.root.right.left.right = new Node(90);
tree.root.right.right.left = new Node(80);
tree.root.right.right.right = new Node(90);
if(tree.isFullTree(tree.root))
372
Chapter 58. Check whether a binary tree is a full binary tree or not
Python
373
Chapter 58. Check whether a binary tree is a full binary tree or not
root.right.right = Node(70);
root.left.left.left = Node(80);
root.left.left.right = Node(90);
root.left.right.left = Node(80);
root.left.right.right = Node(90);
root.right.left.left = Node(80);
root.right.left.right = Node(90);
root.right.right.left = Node(80);
root.right.right.right = Node(90);
if isFullTree(root):
print "The Binary tree is full"
else:
print "Binary tree is not full"
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time complexity of the above code is O(n) where n is number of nodes in given binary tree.
This article is contributed by Gaurav Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : mahaveer2407
Source
https://www.geeksforgeeks.org/check-whether-binary-tree-full-binary-tree-not/
374
Chapter 59
Check whether a binary tree is a full binary tree or not | Iterative Approach - GeeksforGeeks
Given a binary tree containing n nodes. The problem is to check whether the given binary
tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all
nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree,
which has only one child node.
Examples:
Input :
1
/ \
2 3
/ \
4 5
Output : Yes
Input :
1
/ \
2 3
/
4
Output :No
Approach: In the previous post a recursive solution has been discussed. In this post an
375
Chapter 59. Check whether a binary tree is a full binary tree or not | Iterative Approach
iterative approach has been followed. Perform iterative level order traversal of the tree using
queue. For each node encountered, follow the steps given below:
If all the node’s from the queue gets processed without returning false, then return true as
the binary tree is a full binary tree.
376
Chapter 59. Check whether a binary tree is a full binary tree or not | Iterative Approach
q.push(root);
// traverse all the nodes of the binary tree
// level by level until queue is empty
while (!q.empty()) {
// get the pointer to 'node' at front
// of queue
Node* node = q.front();
q.pop();
// if it is a leaf node then continue
if (node->left == NULL && node->right == NULL)
continue;
// if either of the child is not null and the
// other one is null, then binary tree is not
// a full binary tee
if (node->left == NULL || node->right == NULL)
return false;
// push left and right childs of 'node'
// on to the queue 'q'
q.push(node->left);
q.push(node->right);
}
// binary tree is a full binary tee
return true;
}
// Driver program to test above
int main()
{
Node* root = getNode(1);
root->left = getNode(2);
root->right = getNode(3);
root->left->left = getNode(4);
root->left->right = getNode(5);
if (isFullBinaryTree(root))
cout << "Yes";
else
cout << "No";
return 0;
}
Output:
377
Chapter 59. Check whether a binary tree is a full binary tree or not | Iterative Approach
Yes
Source
https://www.geeksforgeeks.org/check-whether-binary-tree-full-binary-tree-not-iterative-approach/
378
Chapter 60
Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution) - Geeks-
forGeeks
Given a Binary Tree, write a function to check whether the given Binary Tree is Complete
Binary Tree or not.
A complete binary tree is a binary tree in which every level, except possibly the last, is
completely filled, and all nodes are as far left as possible. See following examples.
1
/ \
2 3
/
4
1
/ \
2 3
/ \ /
4 5 6
379
Chapter 60. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
1
/ \
2 3
\ / \
4 5 6
1
/ \
2 3
/ \
4 5
The method 2 of level order traversal post can be easily modified to check whether a tree
is Complete or not. To understand the approach, let us first define a term ‘Full Node’. A
node is ‘Full Node’ if both left and right children are not empty (or not NULL).
The approach is to do a level order traversal starting from root. In the traversal, once a
node is found which is NOT a Full Node, all the following nodes must be leaf nodes.
Also, one more thing needs to be checked to handle the below case: If a node has empty left
child, then the right child must be empty.
1
/ \
2 3
\
4
Thanks to Guddu Sharma for suggesting this simple and efficient approach.
C/C++
380
Chapter 60. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
381
Chapter 60. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
{
// If we have seen a non full node, and we see a node
// with non-empty right child, then the given tree is not
// a complete Binary Tree
if(flag == true)
return false;
enQueue(queue, &rear, temp_node->right); // Enqueue Right Child
}
else // If this a non-full node, set the flag as true
flag = true;
}
// If we reach here, then the tree is complete Bianry Tree
return true;
}
/*UTILITY FUNCTIONS*/
struct node** createQueue(int *front, int *rear)
{
struct node **queue =
(struct node **)malloc(sizeof(struct node*)*MAX_Q_SIZE);
*front = *rear = 0;
return queue;
}
void enQueue(struct node **queue, int *rear, struct node *new_node)
{
queue[*rear] = new_node;
(*rear)++;
}
struct node *deQueue(struct node **queue, int *front)
{
(*front)++;
return queue[*front - 1];
}
bool isQueueEmpty(int *front, int *rear)
{
return (*rear == *front);
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
382
Chapter 60. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
/* Let us construct the following Binary Tree which
is not a complete Binary Tree
1
/ \
2 3
/ \ \
4 5 6
*/
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(6);
if ( isCompleteBT(root) == true )
printf ("Complete Binary Tree");
else
printf ("NOT Complete Binary Tree");
return 0;
}
Java
383
Chapter 60. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
384
Chapter 60. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
385
Chapter 60. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
Python
386
Chapter 60. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
387
Chapter 60. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time Complexity: O(n) where n is the number of nodes in given Binary Tree
Auxiliary Space: O(n) for queue.
Source
https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/
388
Chapter 61
10
/ \
20 30
/ \ / \
40 50 60 70
18
/ \
15 30
1
/ \
2 3
\ / \
389
Chapter 61. Check whether a given binary tree is perfect or not
4 5 6
APerfect Binary Treeof height h (where height is number of nodes on path from root to leaf)
has 2h – 1 nodes.
Below is an idea to check whether a given Binary Tree is perfect or not.
1. Find depth of any node (in below tree we find depth of leftmost node). Let this depth
be d.
2. Now recursively traverse the tree and check for following two conditions.
• Every internal node should have both children non-empty
• All leaves are at depth ‘d’
390
Chapter 61. Check whether a given binary tree is perfect or not
391
Chapter 61. Check whether a given binary tree is perfect or not
return(0);
}
Output:
Yes
Source
https://www.geeksforgeeks.org/check-weather-given-binary-tree-perfect-not/
392
Chapter 62
struct node {
int key;
struct node *left,*right,*random;
}
The random pointer points to any random node of the binary tree and can even point to
NULL, clone the given binary tree.
Method 1 (Use Hashing)
The idea is to store mapping from given tree nodes to clone tre node in hashtable. Following
are detailed steps.
1) Recursively traverse the given Binary and copy key value, left pointer and right pointer
to clone tree. While copying, store the mapping from given tree node to clone tree node
in a hashtable. In the following pseudo code, ‘cloneNode’ is currently visited node of clone
tree and ‘treeNode’ is currently visited node of given tree.
cloneNode->key = treeNode->key
cloneNode->left = treeNode->left
cloneNode->right = treeNode->right
map[treeNode] = cloneNode
2) Recursively traverse both trees and set random pointers using entries from hash table.
393
Chapter 62. Clone a Binary Tree with Random Pointers
cloneNode->random = map[treeNode->random]
// A hashmap based C++ program to clone a binary tree with random pointers
#include<iostream>
#include<map>
using namespace std;
/* A binary tree node has data, pointer to left child, a pointer to right
child and a pointer to random node*/
struct Node
{
int key;
struct Node* left, *right, *random;
};
/* Helper function that allocates a new Node with the
given data and NULL left, right and random pointers. */
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->random = temp->right = temp->left = NULL;
return (temp);
}
/* Given a binary tree, print its Nodes in inorder*/
void printInorder(Node* node)
{
if (node == NULL)
return;
/* First recur on left sutree */
printInorder(node->left);
/* then print data of Node and its random */
cout << "[" << node->key << " ";
if (node->random == NULL)
cout << "NULL], ";
else
cout << node->random->key << "], ";
/* now recur on right subtree */
printInorder(node->right);
394
Chapter 62. Clone a Binary Tree with Random Pointers
}
// This function creates clone by copying key and left and right pointers
// This function also stores mapping from given tree node to clone.
Node* copyLeftRightNode(Node* treeNode, map<Node *, Node *> *mymap)
{
if (treeNode == NULL)
return NULL;
Node* cloneNode = newNode(treeNode->key);
(*mymap)[treeNode] = cloneNode;
cloneNode->left = copyLeftRightNode(treeNode->left, mymap);
cloneNode->right = copyLeftRightNode(treeNode->right, mymap);
return cloneNode;
}
// This function copies random node by using the hashmap built by
// copyLeftRightNode()
void copyRandom(Node* treeNode, Node* cloneNode, map<Node *, Node *> *mymap)
{
if (cloneNode == NULL)
return;
cloneNode->random = (*mymap)[treeNode->random];
copyRandom(treeNode->left, cloneNode->left, mymap);
copyRandom(treeNode->right, cloneNode->right, mymap);
}
// This function makes the clone of given tree. It mainly uses
// copyLeftRightNode() and copyRandom()
Node* cloneTree(Node* tree)
{
if (tree == NULL)
return NULL;
map<Node *, Node *> *mymap = new map<Node *, Node *>;
Node* newTree = copyLeftRightNode(tree, mymap);
copyRandom(tree, newTree, mymap);
return newTree;
}
/* Driver program to test above functions*/
int main()
{
//Test No 1
Node *tree = newNode(1);
tree->left = newNode(2);
tree->right = newNode(3);
tree->left->left = newNode(4);
tree->left->right = newNode(5);
tree->random = tree->left->right;
395
Chapter 62. Clone a Binary Tree with Random Pointers
tree->left->left->random = tree;
tree->left->right->random = tree->right;
// Test No 2
// tree = NULL;
// Test No 3
// tree = newNode(1);
// Test No 4
/* tree = newNode(1);
tree->left = newNode(2);
tree->right = newNode(3);
tree->random = tree->right;
tree->left->random = tree;
*/
cout << "Inorder traversal of original binary tree is: \n";
printInorder(tree);
Node *clone = cloneTree(tree);
cout << "\n\nInorder traversal of cloned binary tree is: \n";
printInorder(clone);
return 0;
}
Output:
396
Chapter 62. Clone a Binary Tree with Random Pointers
#include <iostream>
using namespace std;
/* A binary tree node has data, pointer to left child, a pointer to right
child and a pointer to random node*/
struct Node
{
int key;
struct Node* left, *right, *random;
};
/* Helper function that allocates a new Node with the
given data and NULL left, right and random pointers. */
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->random = temp->right = temp->left = NULL;
return (temp);
}
/* Given a binary tree, print its Nodes in inorder*/
void printInorder(Node* node)
{
if (node == NULL)
return;
/* First recur on left sutree */
printInorder(node->left);
397
Chapter 62. Clone a Binary Tree with Random Pointers
/* then print data of Node and its random */
cout << "[" << node->key << " ";
if (node->random == NULL)
cout << "NULL], ";
else
cout << node->random->key << "], ";
/* now recur on right subtree */
printInorder(node->right);
}
// This function creates new nodes cloned tree and puts new cloned node
// in between current node and it's left child
// i.e. if current node is A and it's left child is B ( A --- >> B ),
// then new cloned node with key A wil be created (say cA) and
// it will be put as
// A --- >> cA --- >> B
// Here B can be a NULL or a non-NULL left child
// Right child pointer will be set correctly
// i.e. if for current node A, right child is C in original tree
// (A --- >> C) then corresponding cloned nodes cA and cC will like
// cA ---- >> cC
Node* copyLeftRightNode(Node* treeNode)
{
if (treeNode == NULL)
return NULL;
Node* left = treeNode->left;
treeNode->left = newNode(treeNode->key);
treeNode->left->left = left;
if(left != NULL)
left->left = copyLeftRightNode(left);
treeNode->left->right = copyLeftRightNode(treeNode->right);
return treeNode->left;
}
// This function sets random pointer in cloned tree as per original tree
// i.e. if node A's random pointer points to node B, then
// in cloned tree, cA wil point to cB (cA and cB are new node in cloned
// tree corresponding to node A and B in original tree)
void copyRandomNode(Node* treeNode, Node* cloneNode)
{
if (treeNode == NULL)
return;
if(treeNode->random != NULL)
cloneNode->random = treeNode->random->left;
398
Chapter 62. Clone a Binary Tree with Random Pointers
else
cloneNode->random = NULL;
if(treeNode->left != NULL && cloneNode->left != NULL)
copyRandomNode(treeNode->left->left, cloneNode->left->left);
copyRandomNode(treeNode->right, cloneNode->right);
}
// This function will restore left pointers correctly in
// both original and cloned tree
void restoreTreeLeftNode(Node* treeNode, Node* cloneNode)
{
if (treeNode == NULL)
return;
if (cloneNode->left != NULL)
{
Node* cloneLeft = cloneNode->left->left;
treeNode->left = treeNode->left->left;
cloneNode->left = cloneLeft;
}
else
treeNode->left = NULL;
restoreTreeLeftNode(treeNode->left, cloneNode->left);
restoreTreeLeftNode(treeNode->right, cloneNode->right);
}
//This function makes the clone of given tree
Node* cloneTree(Node* treeNode)
{
if (treeNode == NULL)
return NULL;
Node* cloneNode = copyLeftRightNode(treeNode);
copyRandomNode(treeNode, cloneNode);
restoreTreeLeftNode(treeNode, cloneNode);
return cloneNode;
}
/* Driver program to test above functions*/
int main()
{
/* //Test No 1
Node *tree = newNode(1);
tree->left = newNode(2);
tree->right = newNode(3);
tree->left->left = newNode(4);
tree->left->right = newNode(5);
399
Chapter 62. Clone a Binary Tree with Random Pointers
tree->random = tree->left->right;
tree->left->left->random = tree;
tree->left->right->random = tree->right;
// Test No 2
// Node *tree = NULL;
/*
// Test No 3
Node *tree = newNode(1);
// Test No 4
Node *tree = newNode(1);
tree->left = newNode(2);
tree->right = newNode(3);
tree->random = tree->right;
tree->left->random = tree;
Test No 5
Node *tree = newNode(1);
tree->left = newNode(2);
tree->right = newNode(3);
tree->left->left = newNode(4);
tree->left->right = newNode(5);
tree->right->left = newNode(6);
tree->right->right = newNode(7);
tree->random = tree->left;
*/
// Test No 6
Node *tree = newNode(10);
Node *n2 = newNode(6);
Node *n3 = newNode(12);
Node *n4 = newNode(5);
Node *n5 = newNode(8);
Node *n6 = newNode(11);
Node *n7 = newNode(13);
Node *n8 = newNode(7);
Node *n9 = newNode(9);
tree->left = n2;
tree->right = n3;
tree->random = n2;
n2->left = n4;
n2->right = n5;
n2->random = n8;
n3->left = n6;
n3->right = n7;
n3->random = n5;
n4->random = n9;
n5->left = n8;
400
Chapter 62. Clone a Binary Tree with Random Pointers
n5->right = n9;
n5->random = tree;
n6->random = n9;
n9->random = n8;
/* Test No 7
Node *tree = newNode(1);
tree->left = newNode(2);
tree->right = newNode(3);
tree->left->random = tree;
tree->right->random = tree->left;
*/
cout << "Inorder traversal of original binary tree is: \n";
printInorder(tree);
Node *clone = cloneTree(tree);
cout << "\n\nInorder traversal of cloned binary tree is: \n";
printInorder(clone);
return 0;
}
Output:
This article is contributed by Anurag Singh. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/clone-binary-tree-random-pointers/
401
Chapter 63
402
Chapter 63. Closest leaf to a given node in Binary Tree
Output 2
Closest leaf is 12 through 10.
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to first traverse the subtree rooted with give node and find the closest leaf in
this subtree. Store this distance. Now traverse tree starting from root. If given node x is
in left subtree of root, then find the closest leaf in right subtree, else find the closest left in
left subtree. Below is C++ implementation of this idea.
C++
403
Chapter 63. Closest leaf to a given node in Binary Tree
return;
}
// Recur for left and right subtrees
findLeafDown(root->left, lev+1, minDist);
findLeafDown(root->right, lev+1, minDist);
}
// This function finds if there is closer leaf to x through
// parent node.
int findThroughParent(Node * root, Node *x, int *minDist)
{
// Base cases
if (root == NULL) return -1;
if (root == x) return 0;
// Search x in left subtree of root
int l = findThroughParent(root->left, x, minDist);
// If left subtree has x
if (l != -1)
{
// Find closest leaf in right subtree
findLeafDown(root->right, l+2, minDist);
return l+1;
}
// Search x in right subtree of root
int r = findThroughParent(root->right, x, minDist);
// If right subtree has x
if (r != -1)
{
// Find closest leaf in left subtree
findLeafDown(root->left, r+2, minDist);
return r+1;
}
return -1;
}
// Returns minimum distance of a leaf from given node x
int minimumDistance(Node *root, Node *x)
{
// Initialize result (minimum distance from a leaf)
int minDist = INT_MAX;
// Find closest leaf down to x
404
Chapter 63. Closest leaf to a given node in Binary Tree
findLeafDown(x, 0, &minDist);
// See if there is a closer leaf through parent
findThroughParent(root, x, &minDist);
return minDist;
}
// Driver program
int main ()
{
// Let us create Binary Tree shown in above example
Node *root = newNode(1);
root->left = newNode(12);
root->right = newNode(13);
root->right->left = newNode(14);
root->right->right = newNode(15);
root->right->left->left = newNode(21);
root->right->left->right = newNode(22);
root->right->right->left = newNode(23);
root->right->right->right = newNode(24);
root->right->left->left->left = newNode(1);
root->right->left->left->right = newNode(2);
root->right->left->right->left = newNode(3);
root->right->left->right->right = newNode(4);
root->right->right->left->left = newNode(5);
root->right->right->left->right = newNode(6);
root->right->right->right->left = newNode(7);
root->right->right->right->right = newNode(8);
Node *x = root->right;
cout << "The closest leaf to the node with value "
<< x->key << " is at a distance of "
<< minimumDistance(root, x) << endl;
return 0;
}
Java
405
Chapter 63. Closest leaf to a given node in Binary Tree
{
int key;
Node left, right;
public Node(int key)
{
this.key = key;
left = right = null;
}
}
class Distance
{
int minDis = Integer.MAX_VALUE;
}
class BinaryTree
{
Node root;
// This function finds closest leaf to root. This distance
// is stored at *minDist.
void findLeafDown(Node root, int lev, Distance minDist)
{
// base case
if (root == null)
return;
// If this is a leaf node, then check if it is closer
// than the closest so far
if (root.left == null && root.right == null)
{
if (lev < (minDist.minDis))
minDist.minDis = lev;
return;
}
// Recur for left and right subtrees
findLeafDown(root.left, lev + 1, minDist);
findLeafDown(root.right, lev + 1, minDist);
}
// This function finds if there is closer leaf to x through
// parent node.
int findThroughParent(Node root, Node x, Distance minDist)
{
406
Chapter 63. Closest leaf to a given node in Binary Tree
407
Chapter 63. Closest leaf to a given node in Binary Tree
Output:
Time Complexity of this above solution is O(n) as it does at most two traversals of given
Binary Tree.
This article is contributed by Ekta Goel. Please write comments if you find anything incor-
rect, or you want to share more information about the topic discussed above
408
Chapter 63. Closest leaf to a given node in Binary Tree
Source
https://www.geeksforgeeks.org/closest-leaf-to-a-given-node-in-binary-tree/
409
Chapter 64
410
Chapter 64. Combinatorics on ordered trees
The total number of unlabelled ordered trees having n nodes is equal to the (n – 1)-th
Catalan Number.
Given below are the possible unlabelled ordered trees having 4 nodes. This diagram will
work as a reference example for the next few results.
411
Chapter 64. Combinatorics on ordered trees
C++
412
Chapter 64. Combinatorics on ordered trees
int i, j;
// Caculate value of Binomial
// Coefficient in bottom up manner
for (i = 0; i <= n; i++) {
for (j = 0; j <= min(i, k); j++) {
// Base Cases
if (j == 0 || j == i)
C[i][j] = 1;
// Calculate value using
// previously stored values
else
C[i][j] = C[i - 1][j - 1] + C[i - 1][j];
}
}
return C[n][k];
}
// Function to calculate the number
// of trees with exactly k leaves.
int k_Leaves(int n, int k)
{
int ans = (binomialCoeff(n, k) * binomialCoeff(n, k - 1)) / n;
cout << "Number of trees having 4 edges"
<< " and exactly 2 leaves : " << ans << endl;
return 0;
}
// Function to calculate total number of
// nodes of degree d in these trees.
int numberOfNodes(int n, int d)
{
int ans = binomialCoeff(2 * n - 1 - d, n - 1);
cout << "Number of nodes of degree 1 in"
<< " a tree having 4 edges : " << ans << endl;
return 0;
}
// Function to calculate the number of
// trees in which the root has degree r.
int rootDegreeR(int n, int r)
{
int ans = r * binomialCoeff(2 * n - 1 - r, n - 1);
ans = ans / n;
cout << "Number of trees having 4 edges"
413
Chapter 64. Combinatorics on ordered trees
<< " where root has degree 2 : " << ans << endl;
return 0;
}
// Driver program to test above functions
int main()
{
// Number of trees having 3
// edges and exactly 2 leaves
k_Leaves(3, 2);
// Number of nodes of degree
// 3 in a tree having 4 edges
numberOfNodes(3, 1);
// Number of trees having 3
// edges where root has degree 2
rootDegreeR(3, 2);
return 0;
}
Java
414
Chapter 64. Combinatorics on ordered trees
415
Chapter 64. Combinatorics on ordered trees
C#
416
Chapter 64. Combinatorics on ordered trees
417
Chapter 64. Combinatorics on ordered trees
public static void Main ()
{
// Number of trees having 3
// edges and exactly 2 leaves
k_Leaves(3, 2);
// Number of nodes of degree
// 3 in a tree having 4 edges
numberOfNodes(3, 1);
// Number of trees having 3
// edges where root has degree 2
rootDegreeR(3, 2);
}
}
// This code is contributed by anuj_67.
PHP
<?php
// PHP code to find the number of ordered
// trees with given number of edges and
// leaves
// Function returns value of Binomial
// Coefficient C(n, k)
function binomialCoeff($n, $k)
{
$C = array(array());
$i; $j;
// Caculate value of Binomial
// Coefficient in bottom up manner
for ($i = 0; $i <= $n; $i++) {
for ($j = 0; $j <= min($i, $k); $j++)
{
// Base Cases
if ($j == 0 or $j == $i)
$C[$i][$j] = 1;
// Calculate value using
// previously stored values
else
$C[$i][$j] = $C[$i - 1][$j - 1]
418
Chapter 64. Combinatorics on ordered trees
419
Chapter 64. Combinatorics on ordered trees
Output:
Source
https://www.geeksforgeeks.org/combinatorics-ordered-trees/
420
Chapter 65
Complexity of different
operations in Binary tree,
Binary Search Tree and AVL
tree
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree - Geeks-
forGeeks
In this article, we will discuss complexity of different operations in binary trees including
BST and AVL trees. Before understanding this article, you should have basic idea about:
Binary Tree, Binary Search Tree and AVL Tree.
The main operations in binary tree are: search, insert and delete. We will see the worst
case time complexity of these operations in binary trees.
Binary Tree –
In a binary tree, a node can have maximum two children. Consider the left skewed binary
tree shown in Figure 1.
421
Chapter 65. Complexity of different operations in Binary tree, Binary Search Tree and
AVL tree
• Deletion: For deletion of element 2, we have to traverse all elements to find 2 (assum-
ing we do breadth first traversal). Therefore, deletion in binary tree has worst case
complexity of O(n).
• Searching: For searching element 1, we have to traverse all elements (in order 3, 2,
1). Therefore, searching in binary search tree has worst case complexity of O(n). In
general, time complexity is O(h) where h is height of BST.
• Insertion: For inserting element 0, it must be inserted as left child of 1. Therefore,
we need to traverse all elements (in order 3, 2, 1) to insert 0 which has worst case
complexity of O(n). In general, time complexity is O(h).
• Deletion: For deletion of element 1, we have to traverse all elements to find 1 (in
order 3, 2, 1). Therefore, deletion in binary tree has worst case complexity of O(n).
In general, time complexity is O(h).
422
Chapter 65. Complexity of different operations in Binary tree, Binary Search Tree and
AVL tree
Source
https://www.geeksforgeeks.org/complexity-different-operations-binary-tree-binary-search-tree-avl-tree/
423
Chapter 66
Input Tree
A
/ \
B C
/ \ \
D E F
Output Tree
A--->NULL
/ \
B-->C-->NULL
/ \ \
D-->E-->F-->NULL
We have already discussed O(n^2) time and O approach in Connect nodes at same level as
morris traversal in worst case can be O(n) and calling it to set right pointer can result in
O(n^2) time complexity.
In this post, We have discussed Level Order Traversal with NULL markers which are
needed to mark levels in tree.
C++
424
Chapter 66. Connect Nodes at same Level (Level Order Traversal)
425
Chapter 66. Connect Nodes at same Level (Level Order Traversal)
{
struct Node* node = (struct Node*)
malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = node->nextRight = NULL;
return (node);
}
/* Driver program to test above functions*/
int main()
{
/* Constructed binary tree is
10
/ \
8 2
/ \
3 90
*/
struct Node* root = newnode(10);
root->left = newnode(8);
root->right = newnode(2);
root->left->left = newnode(3);
root->right->right = newnode(90);
// Populates nextRight pointer in all nodes
connect(root);
// Let us check the values of nextRight pointers
printf("Following are populated nextRight pointers in \n"
"the tree (-1 is printed if there is no nextRight) \n");
printf("nextRight of %d is %d \n", root->data,
root->nextRight ? root->nextRight->data : -1);
printf("nextRight of %d is %d \n", root->left->data,
root->left->nextRight ? root->left->nextRight->data : -1);
printf("nextRight of %d is %d \n", root->right->data,
root->right->nextRight ? root->right->nextRight->data : -1);
printf("nextRight of %d is %d \n", root->left->left->data,
root->left->left->nextRight ? root->left->left->nextRight->data : -1);
printf("nextRight of %d is %d \n", root->right->right->data,
root->right->right->nextRight ? root->right->right->nextRight->data : -1);
return 0;
}
Java
426
Chapter 66. Connect Nodes at same Level (Level Order Traversal)
import java.util.LinkedList;
import java.util.Queue;
public class Connect_node_same_level {
// Node class
static class Node {
int data;
Node left, right, nextRight;
Node(int data){
this.data = data;
left = null;
right = null;
nextRight = null;
}
};
// Sets nextRight of all nodes of a tree
static void connect(Node root)
{
Queue<Node> q = new LinkedList<Node>();
q.add(root);
// null marker to represent end of current level
q.add(null);
// Do Level order of tree using NULL markers
while (!q.isEmpty()) {
Node p = q.peek();
q.remove();
if (p != null) {
// next element in queue represents next
// node at current Level
p.nextRight = q.peek();
// push left and right children of current
// node
if (p.left != null)
q.add(p.left);
if (p.right != null)
q.add(p.right);
}
// if queue is not empty, push NULL to mark
// nodes at this level are visited
else if (!q.isEmpty())
q.add(null);
}
427
Chapter 66. Connect Nodes at same Level (Level Order Traversal)
}
/* Driver program to test above functions*/
public static void main(String args[])
{
/* Constructed binary tree is
10
/ \
8 2
/ \
3 90
*/
Node root = new Node(10);
root.left = new Node(8);
root.right = new Node(2);
root.left.left = new Node(3);
root.right.right = new Node(90);
// Populates nextRight pointer in all nodes
connect(root);
// Let us check the values of nextRight pointers
System.out.println("Following are populated nextRight pointers in \n" +
"the tree (-1 is printed if there is no nextRight)");
System.out.println("nextRight of "+ root.data +" is "+
((root.nextRight != null) ? root.nextRight.data : -1));
System.out.println("nextRight of "+ root.left.data+" is "+
((root.left.nextRight != null) ? root.left.nextRight.data : -1));
System.out.println("nextRight of "+ root.right.data+" is "+
((root.right.nextRight != null) ? root.right.nextRight.data : -1));
System.out.println("nextRight of "+ root.left.left.data+" is "+
((root.left.left.nextRight != null) ? root.left.left.nextRight.data : -1));
System.out.println("nextRight of "+ root.right.right.data+" is "+
((root.right.right.nextRight != null) ? root.right.right.nextRight.data : -1));
}
}
// This code is contributed by Sumit Ghosh
Output:
428
Chapter 66. Connect Nodes at same Level (Level Order Traversal)
nextRight of 90 is -1
Source
https://www.geeksforgeeks.org/connect-nodes-level-level-order-traversal/
429
Chapter 67
struct node{
int data;
struct node* left;
struct node* right;
struct node* nextRight;
}
Initially, all the nextRight pointers point to garbage values. Your function should set these
pointers to point next right for each node.
Example
Input Tree
A
/ \
B C
/ \ \
D E F
Output Tree
A--->NULL
/ \
B-->C-->NULL
/ \ \
D-->E-->F-->NULL
430
Chapter 67. Connect nodes at same level
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
struct node *nextRight;
};
void connectRecur(struct node* p);
// Sets the nextRight of root and calls connectRecur()
// for other nodes
void connect (struct node *p)
{
// Set the nextRight for root
p->nextRight = NULL;
// Set the next right for rest of the nodes
// (other than root)
connectRecur(p);
431
Chapter 67. Connect nodes at same level
}
/* Set next right of all descendents of p.
Assumption: p is a compete binary tree */
void connectRecur(struct node* p)
{
// Base case
if (!p)
return;
// Set the nextRight pointer for p's left child
if (p->left)
p->left->nextRight = p->right;
// Set the nextRight pointer for p's right child
// p->nextRight will be NULL if p is the right
// most child at its level
if (p->right)
p->right->nextRight = (p->nextRight)? p->nextRight->left: NULL;
// Set nextRight for other nodes in pre order fashion
connectRecur(p->left);
connectRecur(p->right);
}
/* UTILITY FUNCTIONS */
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newnode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
node->nextRight = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
/* Constructed binary tree is
10
/ \
8 2
432
Chapter 67. Connect nodes at same level
/
3
*/
struct node *root = newnode(10);
root->left = newnode(8);
root->right = newnode(2);
root->left->left = newnode(3);
// Populates nextRight pointer in all nodes
connect(root);
// Let us check the values of nextRight pointers
printf("Following are populated nextRight pointers in the tree "
"(-1 is printed if there is no nextRight) \n");
printf("nextRight of %d is %d \n", root->data,
root->nextRight? root->nextRight->data: -1);
printf("nextRight of %d is %d \n", root->left->data,
root->left->nextRight? root->left->nextRight->data: -1);
printf("nextRight of %d is %d \n", root->right->data,
root->right->nextRight? root->right->nextRight->data: -1);
printf("nextRight of %d is %d \n", root->left->left->data,
root->left->left->nextRight? root->left->left->nextRight->data: -1);
return 0;
}
Java
433
Chapter 67. Connect nodes at same level
434
Chapter 67. Connect nodes at same level
1
/ \
2 3
/ \ / \
4 5 6 7
435
Chapter 67. Connect nodes at same level
/ \ / \
8 9 10 11
See Connect nodes at same level using constant extra space for more solutions.
Source
https://www.geeksforgeeks.org/connect-nodes-at-same-level/
436
Chapter 68
struct node {
int data;
struct node* left;
struct node* right;
struct node* nextRight;
}
Initially, all the nextRight pointers point to garbage values. Your function should set these
pointers to point next right for each node. You can use only constant extra space.
Example
Input Tree
A
/ \
B C
/ \ \
D E F
Output Tree
A--->NULL
/ \
B-->C-->NULL
/ \ \
D-->E-->F-->NULL
437
Chapter 68. Connect nodes at same level using constant extra space
We discussed two different approaches to do it in the previous post. The auxiliary space
required in both of those approaches is not constant. Also, the method 2 discussed there
only works for complete Binary Tree.
In this post, we will first modify the method 2 to make it work for all kind of trees. After
that, we will remove recursion from this method so that the extra space becomes constant.
A Recursive Solution
In the method 2 of previous post, we traversed the nodes in pre order fashion. Instead of
traversing in Pre Order fashion (root, left, right), if we traverse the nextRight node before
the left and right children (root, nextRight, left), then we can make sure that all nodes at
level i have the nextRight set, before the level i+1 nodes. Let us consider the following
example (same example as previous post). The method 2 fails for right child of node 4. In
this method, we make sure that all nodes at the 4’s level (level 2) have nextRight set, before
we try to set the nextRight of 9. So when we set the nextRight of 9, we search for a nonleaf
node on right side of node 4 (getNextRight() does this for us).
1 -------------- Level 0
/ \
2 3 -------------- Level 1
/ \ /
\
4 5 6 7 -------------- Level 2
/ \ / \
8 9 10 11 -------------- Level 3
438
Chapter 68. Connect nodes at same level using constant extra space
/* Before setting nextRight of left and right children, set nextRight
of children of other nodes at same level (because we can access
children of other nodes using p's nextRight only) */
if (p->nextRight != NULL)
connectRecur(p->nextRight);
/* Set the nextRight pointer for p's left child */
if (p->left)
{
if (p->right)
{
p->left->nextRight = p->right;
p->right->nextRight = getNextRight(p);
}
else
p->left->nextRight = getNextRight(p);
/* Recursively call for next level nodes. Note that we call only
for left child. The call for left child will call for right child */
connectRecur(p->left);
}
/* If left child is NULL then first node of next level will either be
p->right or getNextRight(p) */
else if (p->right)
{
p->right->nextRight = getNextRight(p);
connectRecur(p->right);
}
else
connectRecur(getNextRight(p));
}
/* This function returns the leftmost child of nodes at the same level as p.
This function is used to getNExt right of p's right child
If right child of p is NULL then this can also be used for the left child */
struct node *getNextRight(struct node *p)
{
struct node *temp = p->nextRight;
/* Traverse nodes at p's level and find and return
the first node's first child */
while(temp != NULL)
{
if(temp->left != NULL)
return temp->left;
if(temp->right != NULL)
439
Chapter 68. Connect nodes at same level using constant extra space
return temp->right;
temp = temp->nextRight;
}
// If all the nodes at p's level are leaf nodes then return NULL
return NULL;
}
Java
440
Chapter 68. Connect nodes at same level using constant extra space
{
p.left.nextRight = p.right;
p.right.nextRight = getNextRight(p);
}
else
p.left.nextRight = getNextRight(p);
/* Recursively call for next level nodes. Note that we call only
for left child. The call for left child will call for right child */
connectRecur(p.left);
}
/* If left child is NULL then first node of next level will either be
p->right or getNextRight(p) */
else if (p.right != null)
{
p.right.nextRight = getNextRight(p);
connectRecur(p.right);
}
else
connectRecur(getNextRight(p));
}
/* This function returns the leftmost child of nodes at the same
level as p. This function is used to getNExt right of p's right child
If right child of p is NULL then this can also be used for
the left child */
Node getNextRight(Node p)
{
Node temp = p.nextRight;
/* Traverse nodes at p's level and find and return
the first node's first child */
while (temp != null)
{
if (temp.left != null)
return temp.left;
if (temp.right != null)
return temp.right;
temp = temp.nextRight;
}
// If all the nodes at p's level are leaf nodes then return NULL
return null;
}
/* Driver program to test the above functions */
public static void main(String args[])
441
Chapter 68. Connect nodes at same level using constant extra space
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(8);
tree.root.right = new Node(2);
tree.root.left.left = new Node(3);
tree.root.right.right = new Node(90);
// Populates nextRight pointer in all nodes
tree.connectRecur(tree.root);
// Let us check the values of nextRight pointers
int a = tree.root.nextRight != null ?
tree.root.nextRight.data : -1;
int b = tree.root.left.nextRight != null ?
tree.root.left.nextRight.data : -1;
int c = tree.root.right.nextRight != null ?
tree.root.right.nextRight.data : -1;
int d = tree.root.left.left.nextRight != null ?
tree.root.left.left.nextRight.data : -1;
int e = tree.root.right.right.nextRight != null ?
tree.root.right.right.nextRight.data : -1;
// Now lets print the values
System.out.println("Following are populated nextRight pointers in "
+ " the tree(-1 is printed if there is no nextRight)");
System.out.println("nextRight of " + tree.root.data + " is " + a);
System.out.println("nextRight of " + tree.root.left.data + " is " + b);
System.out.println("nextRight of " + tree.root.right.data + " is " + c);
System.out.println("nextRight of " + tree.root.left.left.data +
" is " + d);
System.out.println("nextRight of " + tree.root.right.right.data +
" is " + e);
}
}
// This code has been contributed by Mayank Jaiswal
An Iterative Solution
The recursive approach discussed above can be easily converted to iterative. In the iterative
version, we use nested loop. The outer loop, goes through all the levels and the inner loop
goes through all the nodes at every level. This solution uses constant space.
C
#include <stdio.h>
#include <stdlib.h>
442
Chapter 68. Connect nodes at same level using constant extra space
struct node
{
int data;
struct node *left;
struct node *right;
struct node *nextRight;
};
/* This function returns the leftmost child of nodes at the same level as p.
This function is used to getNExt right of p's right child
If right child of is NULL then this can also be sued for the left child */
struct node *getNextRight(struct node *p)
{
struct node *temp = p->nextRight;
/* Traverse nodes at p's level and find and return
the first node's first child */
while (temp != NULL)
{
if (temp->left != NULL)
return temp->left;
if (temp->right != NULL)
return temp->right;
temp = temp->nextRight;
}
// If all the nodes at p's level are leaf nodes then return NULL
return NULL;
}
/* Sets nextRight of all nodes of a tree with root as p */
void connect(struct node* p)
{
struct node *temp;
if (!p)
return;
// Set nextRight for root
p->nextRight = NULL;
// set nextRight of all levels one by one
while (p != NULL)
{
struct node *q = p;
/* Connect all childrem nodes of p and children nodes of all other nodes
at same level as p */
443
Chapter 68. Connect nodes at same level using constant extra space
while (q != NULL)
{
// Set the nextRight pointer for p's left child
if (q->left)
{
// If q has right child, then right child is nextRight of
// p and we also need to set nextRight of right child
if (q->right)
q->left->nextRight = q->right;
else
q->left->nextRight = getNextRight(q);
}
if (q->right)
q->right->nextRight = getNextRight(q);
// Set nextRight for other nodes in pre order fashion
q = q->nextRight;
}
// start from the first node of next level
if (p->left)
p = p->left;
else if (p->right)
p = p->right;
else
p = getNextRight(p);
}
}
/* UTILITY FUNCTIONS */
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newnode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
node->nextRight = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
444
Chapter 68. Connect nodes at same level using constant extra space
/* Constructed binary tree is
10
/ \
8 2
/ \
3 90
*/
struct node *root = newnode(10);
root->left = newnode(8);
root->right = newnode(2);
root->left->left = newnode(3);
root->right->right = newnode(90);
// Populates nextRight pointer in all nodes
connect(root);
// Let us check the values of nextRight pointers
printf("Following are populated nextRight pointers in the tree "
"(-1 is printed if there is no nextRight) \n");
printf("nextRight of %d is %d \n", root->data,
root->nextRight? root->nextRight->data: -1);
printf("nextRight of %d is %d \n", root->left->data,
root->left->nextRight? root->left->nextRight->data: -1);
printf("nextRight of %d is %d \n", root->right->data,
root->right->nextRight? root->right->nextRight->data: -1);
printf("nextRight of %d is %d \n", root->left->left->data,
root->left->left->nextRight? root->left->left->nextRight->data: -1);
printf("nextRight of %d is %d \n", root->right->right->data,
root->right->right->nextRight? root->right->right->nextRight->data: -1);
getchar();
return 0;
}
Java
445
Chapter 68. Connect nodes at same level using constant extra space
data = item;
left = right = nextRight = null;
}
}
class BinaryTree
{
Node root;
/* This function returns the leftmost child of nodes at the same level
as p. This function is used to getNExt right of p's right child
If right child of is NULL then this can also be sued for the
left child */
Node getNextRight(Node p)
{
Node temp = p.nextRight;
/* Traverse nodes at p's level and find and return
the first node's first child */
while (temp != null)
{
if (temp.left != null)
return temp.left;
if (temp.right != null)
return temp.right;
temp = temp.nextRight;
}
// If all the nodes at p's level are leaf nodes then return NULL
return null;
}
/* Sets nextRight of all nodes of a tree with root as p */
void connect(Node p) {
Node temp = null;
if (p == null)
return;
// Set nextRight for root
p.nextRight = null;
// set nextRight of all levels one by one
while (p != null)
{
Node q = p;
/* Connect all childrem nodes of p and children nodes of all other
446
Chapter 68. Connect nodes at same level using constant extra space
447
Chapter 68. Connect nodes at same level using constant extra space
// Populates nextRight pointer in all nodes
tree.connect(tree.root);
// Let us check the values of nextRight pointers
int a = tree.root.nextRight != null ?
tree.root.nextRight.data : -1;
int b = tree.root.left.nextRight != null ?
tree.root.left.nextRight.data : -1;
int c = tree.root.right.nextRight != null ?
tree.root.right.nextRight.data : -1;
int d = tree.root.left.left.nextRight != null ?
tree.root.left.left.nextRight.data : -1;
int e = tree.root.right.right.nextRight != null ?
tree.root.right.right.nextRight.data : -1;
// Now lets print the values
System.out.println("Following are populated nextRight pointers in "
+ " the tree(-1 is printed if there is no nextRight)");
System.out.println("nextRight of " + tree.root.data + " is " + a);
System.out.println("nextRight of " + tree.root.left.data
+ " is " + b);
System.out.println("nextRight of " + tree.root.right.data +
" is " + c);
System.out.println("nextRight of " + tree.root.left.left.data +
" is " + d);
System.out.println("nextRight of " + tree.root.right.right.data +
" is " + e);
}
}
// This code has been contributed by Mayank Jaiswal
Output:
Source
https://www.geeksforgeeks.org/connect-nodes-at-same-level-with-o1-extra-space/
448
Chapter 69
mat[i][j] = 1 if i is ancestor of j
mat[i][j] = 0, otherwise
Examples:
449
Chapter 69. Construct Ancestor Matrix from a Given Binary Tree
0 0 0 0 0 0
0 0 0 0 0 0
1 1 1 1 1 0
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to traverse the tree. While traversing, keep track of ancestors in an array. When
we visit a node, we add it to ancestor array and consider corresponding row in adjacency
matrix. We mark all ancestors in its row as 1. Once a node and all its children are processed,
we remove the node from ancestor array.
Below is C++ implementation of above idea.
450
Chapter 69. Construct Ancestor Matrix from a Given Binary Tree
451
Chapter 69. Construct Ancestor Matrix from a Given Binary Tree
root->right = newnode(2);
root->left->left = newnode(0);
root->left->right = newnode(4);
root->right->left = newnode(3);
ancestorMatrix(root);
return 0;
}
Output:
0 0 0 0 0 0
1 0 0 0 1 0
0 0 0 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0
1 1 1 1 1 0
Source
https://www.geeksforgeeks.org/construct-ancestor-matrix-from-a-given-binary-tree/
452
Chapter 70
10
/ \
5 40
/ \ \
1 7 50
We have discussed O(n^2) and O(n) recursive solutions in the previous post. Following is a
stack based iterative solution that works in O(n) time.
1. Create an empty stack.
2. Make the first value as root. Push it to the stack.
3. Keep on popping while the stack is not empty and the next value is greater than stack’s
top value. Make this value as the right child of the last popped node. Push the new node
to the stack.
4. If the next value is less than the stack’s top value, make this value as the left child of
the stack’s top node. Push the new node to the stack.
5. Repeat steps 2 and 3 until there are items remaining in pre[].
C
453
Chapter 70. Construct BST from given preorder traversal | Set 2
454
Chapter 70. Construct BST from given preorder traversal | Set 2
{
return stack->top == -1;
}
// A utility function to push an item to stack
void push( Stack* stack, Node* item )
{
if( isFull( stack ) )
return;
stack->array[ ++stack->top ] = item;
}
// A utility function to remove an item from stack
Node* pop( Stack* stack )
{
if( isEmpty( stack ) )
return NULL;
return stack->array[ stack->top-- ];
}
// A utility function to get top node of stack
Node* peek( Stack* stack )
{
return stack->array[ stack->top ];
}
// The main function that constructs BST from pre[]
Node* constructTree ( int pre[], int size )
{
// Create a stack of capacity equal to size
Stack* stack = createStack( size );
// The first element of pre[] is always root
Node* root = newNode( pre[0] );
// Push root
push( stack, root );
int i;
Node* temp;
// Iterate through rest of the size-1 items of given preorder array
for ( i = 1; i < size; ++i )
{
temp = NULL;
/* Keep on popping while the next value is greater than
stack's top value. */
455
Chapter 70. Construct BST from given preorder traversal | Set 2
Java
456
Chapter 70. Construct BST from given preorder traversal | Set 2
457
Chapter 70. Construct BST from given preorder traversal | Set 2
temp = s.peek();
temp.left = new Node(pre[i]);
s.push(temp.left);
}
}
return root;
}
// A utility function to print inorder traversal of a Binary Tree
void printInorder(Node node) {
if (node == null) {
return;
}
printInorder(node.left);
System.out.print(node.data + " ");
printInorder(node.right);
}
// Driver program to test above functions
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
int pre[] = new int[]{10, 5, 1, 7, 40, 50};
int size = pre.length;
Node root = tree.constructTree(pre, size);
System.out.println("Inorder traversal of the constructed tree is ");
tree.printInorder(root);
}
}
// This code has been contributed by Mayank Jaiswal
Output:
1 5 7 10 40 50
Time Complexity: O(n). The complexity looks more from first look. If we take a closer look,
we can observe that every item is pushed and popped only once. So at most 2n push/pop
operations are performed in the main loops of constructTree(). Therefore, time complexity
is O(n).
Source
https://www.geeksforgeeks.org/construct-bst-from-given-preorder-traversal-set-2/
458
Chapter 71
The idea is to use a queue to construct tree. Every element of queue has a structure say
NodeDetails which stores details of a tree node. The details are pointer to the node, and
two variables min and max where min stores the lower limit for the node values which can
be a part of the left subtree and max stores the upper limit for the node values which can
be a part of the right subtree for the specified node in NodeDetails structure variable. For
the 1st array value arr[0], create a node and then create a NodeDetails structure having
pointer to this node and min = INT_MIN and max = INT_MAX. Add this structure
variable to a queue. This Node will be the root of the tree. Move to 2nd element in arr[]
and then perform the following steps:
459
Chapter 71. Construct BST from its given level order traversal
2. Check whether the current array element can be a left child of the node in temp
with the help of min and temp.node data values. If it can, then create a new
NodeDetails structure for this new array element value with its proper ‘min’ and
‘max’ values and push it to the queue, make this new node as the left child of temp’s
node and move to next element in arr[].
3. Check whether the current array element can be a right child of the node in temp
with the help of max and temp.node data values. If it can, then create a new
NodeDetails structure for this new array element value with its proper ‘min’ and
‘max’ values and push it to the queue, make this new node as the right child of temp’s
node and move to next element in arr[].
4. Repeat steps 1, 2 and 3 until there are no more elements in arr[].
For a left child node, its min value will be its parent’s ‘min’ value and max value will be
the data value of its parent node. For a right child node, its min value will be the data
value of its parent node and max value will be its parent’s ‘max’ value.
Below is C++ implementation of above approach:
460
Chapter 71. Construct BST from its given level order traversal
461
Chapter 71. Construct BST from its given level order traversal
462
Chapter 71. Construct BST from its given level order traversal
{
int arr[] = {7, 4, 12, 3, 6, 8, 1, 5, 10};
int n = sizeof(arr) / sizeof(arr[0]);
Node *root = constructBst(arr, n);
cout << "Inorder Traversal: ";
inorderTraversal(root);
return 0;
}
Output:
Inorder Traversal: 1 3 4 5 6 7 8 10 12
Source
https://www.geeksforgeeks.org/construct-bst-given-level-order-traversal/
463
Chapter 72
Input : "1(2)(3)"
Output : 1 2 3
Explanation :
1
/ \
2 3
Explanation: first pair of parenthesis contains
left subtree and second one contains the right
subtree. Preorder of above tree is "1 2 3".
Input : "4(2(3)(1))(6(5))"
Output : 4 2 3 1 6 5
Explanation :
4
/ \
2 6
/ \ /
464
Chapter 72. Construct Binary Tree from String with bracket representation
3 1 5
We know first character in string is root. Substring inside the first adjacent pair of paren-
thesis is for left subtree and substring inside second pair of parenthesis is for right subtree
as in the below diagram.
We need to find the substring corresponding to left subtree and substring corresponding to
right subtree and then recursively call on both of the substrings.
For this first find the index of starting index and end index of each substring.
To find the index of closing parenthesis of left subtree substring, use a stack. Lets the
found index is stored in index variable.
465
Chapter 72. Construct Binary Tree from String with bracket representation
return;
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
// functin to return the index of close parenthesis
int findIndex(string str, int si, int ei)
{
if (si > ei)
return -1;
// Inbuilt stack
stack<char> s;
for (int i = si; i <= ei; i++) {
// if open parenthesis, push it
if (str[i] == '(')
s.push(str[i]);
// if close parenthesis
else if (str[i] == ')') {
if (s.top() == '(') {
s.pop();
// if stack is empty, this is
// the required index
if (s.empty())
return i;
}
}
}
// if not found return -1
return -1;
}
// function to construct tree from string
Node* treeFromString(string str, int si, int ei)
{
// Base case
if (si > ei)
return NULL;
// new root
Node* root = newNode(str[si] - '0');
int index = -1;
466
Chapter 72. Construct Binary Tree from String with bracket representation
Output:
4 2 3 1 6 5
Source
https://www.geeksforgeeks.org/construct-binary-tree-string-bracket-representation/
467
Chapter 73
468
Chapter 73. Construct Binary Tree from given Parent Array representation
We strongly recommend to minimize your browser and try this yourself first.
A Simple Solution to recursively construct by first searching the current root, then recur-
ring for the found indexes (there can be at most two indexes) and making them left and
right subtrees of root. This solution takes O(n2 ) as we have to linearly search for every
node.
An Efficient Solution can solve the above problem in O(n) time. The idea is to use extra
space. An array created[0..n-1] is used to keep track of created nodes.
createTree(parent[], n)
1. Create an array of pointers say created[0..n-1]. The value of created[i] is NULL if node
for index i is not created, else value is pointer to the created node.
2. Do following for every index i of given array
createNode(parent, i, created)
createNode(parent[], i, crated[])
C++
469
Chapter 73. Construct Binary Tree from given Parent Array representation
470
Chapter 73. Construct Binary Tree from given Parent Array representation
471
Chapter 73. Construct Binary Tree from given Parent Array representation
Java
472
Chapter 73. Construct Binary Tree from given Parent Array representation
p.left = created[i];
else // If second child
p.right = created[i];
}
/* Creates tree from parent[0..n-1] and returns root of
the created tree */
Node createTree(int parent[], int n)
{
// Create an array created[] to keep track
// of created nodes, initialize all entries
// as NULL
Node[] created = new Node[n];
for (int i = 0; i < n; i++)
created[i] = null;
for (int i = 0; i < n; i++)
createNode(parent, i, created);
return root;
}
//For adding new line in a program
void newLine()
{
System.out.println("");
}
// Utility function to do inorder traversal
void inorder(Node node)
{
if (node != null)
{
inorder(node.left);
System.out.print(node.key + " ");
inorder(node.right);
}
}
// Driver method
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
int parent[] = new int[]{-1, 0, 0, 1, 1, 3, 5};
int n = parent.length;
Node node = tree.createTree(parent, n);
473
Chapter 73. Construct Binary Tree from given Parent Array representation
Python
474
Chapter 73. Construct Binary Tree from given Parent Array representation
p.left = created[i]
# If second child
else:
p.right = created[i]
# Creates tree from parent[0..n-1] and returns root of the
# created tree
def createTree(parent):
n = len(parent)
# Create and array created[] to keep track
# of created nodes, initialize all entries as None
created = [None for i in range(n+1)]
root = [None]
for i in range(n):
createNode(parent, i, created, root)
return root[0]
#Inorder traversal of tree
def inorder(root):
if root is not None:
inorder(root.left)
print root.key,
inorder(root.right)
# Driver Method
parent = [-1, 0, 0, 1, 1, 3, 5]
root = createTree(parent)
print "Inorder Traversal of constructed tree"
inorder(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
< Similar Problem: Find Height of Binary Tree represented by Parent array
Source
https://www.geeksforgeeks.org/construct-a-binary-tree-from-parent-array-representation/
475
Chapter 74
Construct Complete Binary Tree from its Linked List Representation - GeeksforGeeks
Given Linked List Representation of Complete Binary Tree, construct the Binary tree. A
complete binary tree can be represented in an array in the following approach.
If root node is stored at index i, its left, and right children are stored at indices 2*i+1, 2*i+2
respectively.
Suppose tree is represented by a linked list in same way, how do we convert this into normal
linked representation of binary tree where every node has data, left and right pointers? In
the linked list representation, we cannot directly access the children of the current node
unless we traverse the list.
We are mainly given level order traversal in sequential access form. We know head of linked
list is always is root of the tree. We take the first node as root and we also know that the
476
Chapter 74. Construct Complete Binary Tree from its Linked List Representation
next two nodes are left and right children of root. So we know partial Binary Tree. The idea
is to do Level order traversal of the partially built Binary Tree using queue and traverse the
linked list at the same time. At every step, we take the parent node from queue, make next
two nodes of linked list as children of the parent node, and enqueue the next two nodes to
queue.
1. Create an empty queue.
2. Make the first node of the list as root, and enqueue it to the queue.
3. Until we reach the end of the list, do the following.
………a. Dequeue one node from the queue. This is the current parent.
………b. Traverse two nodes in the list, add them as children of the current parent.
………c. Enqueue the two nodes into the queue.
Below is the code which implements the same in C++.
C++
// C++ program to create a Complete Binary tree from its Linked List
// Representation
#include <iostream>
#include <string>
#include <queue>
using namespace std;
// Linked list node
struct ListNode
{
int data;
ListNode* next;
};
// Binary tree node structure
struct BinaryTreeNode
{
int data;
BinaryTreeNode *left, *right;
};
// Function to insert a node at the beginning of the Linked List
void push(struct ListNode** head_ref, int new_data)
{
// allocate node and assign data
struct ListNode* new_node = new ListNode;
new_node->data = new_data;
// link the old list off the new node
new_node->next = (*head_ref);
// move the head to point to the new node
477
Chapter 74. Construct Complete Binary Tree from its Linked List Representation
(*head_ref) = new_node;
}
// method to create a new binary tree node from the given data
BinaryTreeNode* newBinaryTreeNode(int data)
{
BinaryTreeNode *temp = new BinaryTreeNode;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// converts a given linked list representing a complete binary tree into the
// linked representation of binary tree.
void convertList2Binary(ListNode *head, BinaryTreeNode* &root)
{
// queue to store the parent nodes
queue<BinaryTreeNode *> q;
// Base Case
if (head == NULL)
{
root = NULL; // Note that root is passed by reference
return;
}
// 1.) The first node is always the root node, and add it to the queue
root = newBinaryTreeNode(head->data);
q.push(root);
// advance the pointer to the next node
head = head->next;
// until the end of linked list is reached, do the following steps
while (head)
{
// 2.a) take the parent node from the q and remove it from q
BinaryTreeNode* parent = q.front();
q.pop();
// 2.c) take next two nodes from the linked list. We will add
// them as children of the current parent node in step 2.b. Push them
// into the queue so that they will be parents to the future nodes
BinaryTreeNode *leftChild = NULL, *rightChild = NULL;
leftChild = newBinaryTreeNode(head->data);
q.push(leftChild);
head = head->next;
if (head)
478
Chapter 74. Construct Complete Binary Tree from its Linked List Representation
{
rightChild = newBinaryTreeNode(head->data);
q.push(rightChild);
head = head->next;
}
// 2.b) assign the left and right children of parent
parent->left = leftChild;
parent->right = rightChild;
}
}
// Utility function to traverse the binary tree after conversion
void inorderTraversal(BinaryTreeNode* root)
{
if (root)
{
inorderTraversal( root->left );
cout << root->data << " ";
inorderTraversal( root->right );
}
}
// Driver program to test above functions
int main()
{
// create a linked list shown in above diagram
struct ListNode* head = NULL;
push(&head, 36); /* Last node of Linked List */
push(&head, 30);
push(&head, 25);
push(&head, 15);
push(&head, 12);
push(&head, 10); /* First node of Linked List */
BinaryTreeNode *root;
convertList2Binary(head, root);
cout << "Inorder Traversal of the constructed Binary Tree is: \n";
inorderTraversal(root);
return 0;
}
Java
// Java program to create complete Binary Tree from its Linked List
// representation
479
Chapter 74. Construct Complete Binary Tree from its Linked List Representation
480
Chapter 74. Construct Complete Binary Tree from its Linked List Representation
481
Chapter 74. Construct Complete Binary Tree from its Linked List Representation
// parent
parent.left = leftChild;
parent.right = rightChild;
}
return node;
}
// Utility function to traverse the binary tree
// after conversion
void inorderTraversal(BinaryTreeNode node)
{
if (node != null)
{
inorderTraversal(node.left);
System.out.print(node.data + " ");
inorderTraversal(node.right);
}
}
// Driver program to test above functions
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.push(36); /* Last node of Linked List */
tree.push(30);
tree.push(25);
tree.push(15);
tree.push(12);
tree.push(10); /* First node of Linked List */
BinaryTreeNode node = tree.convertList2Binary(tree.root);
System.out.println("Inorder Traversal of the"+
" constructed Binary Tree is:");
tree.inorderTraversal(node);
}
}
// This code has been contributed by Mayank Jaiswal
Python
482
Chapter 74. Construct Complete Binary Tree from its Linked List Representation
483
Chapter 74. Construct Complete Binary Tree from its Linked List Representation
484
Chapter 74. Construct Complete Binary Tree from its Linked List Representation
print "Inorder Traversal of the contructed Binary Tree is:"
conv.inorderTraversal(conv.root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time Complexity: Time complexity of the above solution is O(n) where n is the number
of nodes.
This article is compiled by Ravi Chandra Enaganti. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/given-linked-list-representation-of-complete-tree-convert-it-to-linked-representation
485
Chapter 75
Construct Full Binary Tree from given preorder and postorder traversals - GeeksforGeeks
Given two arrays that represent preorder and postorder traversals of a full binary tree,
construct the binary tree.
A Full Binary Tree is a binary tree where every node has either 0 or 2 children
Following are examples of Full Trees.
1
/ \
2 3
/ \ / \
4 5 6 7
1
/ \
2 3
/ \
4 5
/ \
6 7
1
/ \
486
Chapter 75. Construct Full Binary Tree from given preorder and postorder traversals
2 3
/ \ / \
4 5 6 7
/ \
8 9
It is not possible to construct a general Binary Tree from preorder and postorder traversals
(See this). But if know that the Binary Tree is Full, we can construct the tree without
ambiguity. Let us understand this with the help of following example.
Let us consider the two given arrays as pre[] = {1, 2, 4, 8, 9, 5, 3, 6, 7} and post[] = {8, 9,
4, 5, 2, 6, 7, 3, 1};
In pre[], the leftmost element is root of tree. Since the tree is full and array size is more
than 1. The value next to 1 in pre[], must be left child of root. So we know 1 is root and
2 is left child. How to find the all nodes in left subtree? We know 2 is root of all nodes in
left subtree. All nodes before 2 in post[] must be in left subtree. Now we know 1 is root,
elements {8, 9, 4, 5, 2} are in left subtree, and the elements {6, 7, 3} are in right subtree.
1
/ \
/ \
{8, 9, 4, 5, 2} {6, 7, 3}
We recursively follow the above approach and get the following tree.
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
487
Chapter 75. Construct Full Binary Tree from given preorder and postorder traversals
{
int data;
struct node *left;
struct node *right;
};
// A utility function to create a node
struct node* newNode (int data)
{
struct node* temp = (struct node *) malloc( sizeof(struct node) );
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// A recursive function to construct Full from pre[] and post[].
// preIndex is used to keep track of index in pre[].
// l is low index and h is high index for the current subarray in post[]
struct node* constructTreeUtil (int pre[], int post[], int* preIndex,
int l, int h, int size)
{
// Base case
if (*preIndex >= size || l > h)
return NULL;
// The first node in preorder traversal is root. So take the node at
// preIndex from preorder and make it root, and increment preIndex
struct node* root = newNode ( pre[*preIndex] );
++*preIndex;
// If the current subarry has only one element, no need to recur
if (l == h)
return root;
// Search the next element of pre[] in post[]
int i;
for (i = l; i <= h; ++i)
if (pre[*preIndex] == post[i])
break;
// Use the index of element found in postorder to divide postorder array in
// two parts. Left subtree and right subtree
if (i <= h)
{
root->left = constructTreeUtil (pre, post, preIndex, l, i, size);
root->right = constructTreeUtil (pre, post, preIndex, i + 1, h, size);
488
Chapter 75. Construct Full Binary Tree from given preorder and postorder traversals
}
return root;
}
// The main function to construct Full Binary Tree from given preorder and
// postorder traversals. This function mainly uses constructTreeUtil()
struct node *constructTree (int pre[], int post[], int size)
{
int preIndex = 0;
return constructTreeUtil (pre, post, &preIndex, 0, size - 1, size);
}
// A utility function to print inorder traversal of a Binary Tree
void printInorder (struct node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
// Driver program to test above functions
int main ()
{
int pre[] = {1, 2, 4, 8, 9, 5, 3, 6, 7};
int post[] = {8, 9, 4, 5, 2, 6, 7, 3, 1};
int size = sizeof( pre ) / sizeof( pre[0] );
struct node *root = constructTree(pre, post, size);
printf("Inorder traversal of the constructed tree: \n");
printInorder(root);
return 0;
}
Java
489
Chapter 75. Construct Full Binary Tree from given preorder and postorder traversals
{
int data;
node left, right;
public node(int data)
{
this.data = data;
}
}
// A recursive function to construct Full
// from pre[] and post[]. preIndex is used
// to keep track of index in pre[]. l is
// low index and h is high index for the
// current subarray in post[]
static node constructTreeUtil(int pre[], int post[], int l,
int h, int size)
{
// Base case
if (preindex >= size || l > h)
return null;
// The first node in preorder traversal is
// root. So take the node at preIndex from
// preorder and make it root, and increment
// preIndex
node root = new node(pre[preindex]);
preindex++;
// If the current subarry has only one
// element, no need to recur or
// preIndex > size after incrementing
if (l == h || preindex >= size)
return root;
int i;
// Search the next element of pre[] in post[]
for (i = l; i <= h; i++)
{
if (post[i] == pre[preindex])
break;
}
// Use the index of element found in
// postorder to divide postorder array
// in two parts. Left subtree and right subtree
if (i <= h)
{
490
Chapter 75. Construct Full Binary Tree from given preorder and postorder traversals
Output:
491
Chapter 75. Construct Full Binary Tree from given preorder and postorder traversals
Source
https://www.geeksforgeeks.org/full-and-complete-binary-tree-from-given-preorder-and-postorder-traversals/
492
Chapter 76
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror
tree - GeeksforGeeks
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree,
we need to write a program to construct the binary tree using these two Preorder traversals.
A Full Binary Tree is a binary tree where every node has either 0 or 2 children.
Note: It is not possible to construct a general binary tree using these two traversal. But
we can create a full binary tree using the above traversals without any ambiguity. For more
details refer to this article.
Examples:
Output : 1
/ \
2 3
/ \ / \
4 5 6 7
493
Chapter 76. Construct Full Binary Tree using its Preorder traversal and Preorder
traversal of its mirror tree
In both preOrder[] and preOrderMirror[], the leftmost element is root of tree. Since
the tree is full and array size is more than 1. The value next to 1 in preOrder[], must
be left child of root and value next to 1 in preOrderMirror[] must be right child of
root. So we know 1 is root and 2 is left child and 3 is the right child. How to find the
all nodes in left subtree? We know 2 is root of all nodes in left subtree and 3 is root
of all nodes in right subtree. All nodes from and 2 in preOrderMirror[] must be in left
subtree of root node 1 and all node after 3 and before 2 in preOrderMirror[] must be
in right subtree of root node 1. Now we know 1 is root, elements {2, 5, 4} are in left
subtree, and the elements {3, 7, 6} are in the right subtree.
1
/ \
/ \
{2,5,4} {3,7,6}
We will recursively follow the above approach and get the below tree:
1
/ \
2 3
/ \ / \
4 5 6 7
494
Chapter 76. Construct Full Binary Tree using its Preorder traversal and Preorder
traversal of its mirror tree
}
// A utility function to print inorder traversal
// of a Binary Tree
void printInorder(Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
// A recursive function to construct Full binary tree
// from pre[] and preM[]. preIndex is used to keep
// track of index in pre[]. l is low index and h is high
//index for the current subarray in preM[]
Node* constructBinaryTreeUtil(int pre[], int preM[],
int &preIndex, int l,int h,int size)
{
// Base case
if (preIndex >= size || l > h)
return NULL;
// The first node in preorder traversal is root.
// So take the node at preIndex from preorder and
// make it root, and increment preIndex
Node* root = newNode(pre[preIndex]);
++(preIndex);
// If the current subarry has only one element,
// no need to recur
if (l == h)
return root;
// Search the next element of pre[] in preM[]
int i;
for (i = l; i <= h; ++i)
if (pre[preIndex] == preM[i])
break;
// construct left and right subtrees recursively
if (i <= h)
{
root->left = constructBinaryTreeUtil (pre, preM,
preIndex, i, h, size);
root->right = constructBinaryTreeUtil (pre, preM,
495
Chapter 76. Construct Full Binary Tree using its Preorder traversal and Preorder
traversal of its mirror tree
Output:
4 2 5 1 6 3 7
496
Chapter 76. Construct Full Binary Tree using its Preorder traversal and Preorder
traversal of its mirror tree
Source
https://www.geeksforgeeks.org/construct-full-binary-tree-using-preorder-traversal-preorder-traversal-mirror-tree/
497
Chapter 77
The idea used in Construction of Tree from given Inorder and Preorder traversals can be
used here. Let the given array is {1, 5, 10, 40, 30, 15, 28, 20}. The maximum element in
given array must be root. The elements on left side of the maximum element are in left
subtree and elements on right side are in right subtree.
498
Chapter 77. Construct Special Binary Tree from given Inorder traversal
40
/ \
{1,5,10} {30,15,28,20}
We recursively follow above step for left and right subtrees, and finally get the following
tree.
40
/ \
10 30
/ \
5 28
/ / \
1 15 20
Algorithm: buildTree()
1) Find index of the maximum element in array. The maximum element must be root of
Binary Tree.
2) Create a new tree node ‘root’ with the data as the maximum value found in step 1.
3) Call buildTree for elements before the maximum element and make the built tree as left
subtree of ‘root’.
5) Call buildTree for elements after the maximum element and make the built tree as right
subtree of ‘root’.
6) return ‘root’.
Implementation: Following is the implementation of the above algorithm.
C/C++
499
Chapter 77. Construct Special Binary Tree from given Inorder traversal
500
Chapter 77. Construct Special Binary Tree from given Inorder traversal
Java
501
Chapter 77. Construct Special Binary Tree from given Inorder traversal
502
Chapter 77. Construct Special Binary Tree from given Inorder traversal
/* Function to find index of the maximum value in arr[start...end] */
int max(int arr[], int strt, int end)
{
int i, max = arr[strt], maxind = strt;
for (i = strt + 1; i <= end; i++)
{
if (arr[i] > max)
{
max = arr[i];
maxind = i;
}
}
return maxind;
}
/* This funtcion is here just to test buildTree() */
void printInorder(Node node)
{
if (node == null)
return;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
System.out.print(node.data + " ");
/* now recur on right child */
printInorder(node.right);
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
/* Assume that inorder traversal of following tree is given
40
/ \
10 30
/ \
5 28 */
int inorder[] = new int[]{5, 10, 40, 30, 28};
int len = inorder.length;
Node mynode = tree.buildTree(inorder, 0, len - 1, tree.root);
/* Let us test the built tree by printing Inorder traversal */
System.out.println("Inorder traversal of the constructed tree is ");
503
Chapter 77. Construct Special Binary Tree from given Inorder traversal
tree.printInorder(mynode);
}
}
// This code has been contributed by Mayank Jaiswal
Output:
Source
https://www.geeksforgeeks.org/construct-binary-tree-from-inorder-traversal/
504
Chapter 78
A
/ \
/ \
D B E F C
A
/ \
/ \
B C
/ \ /
/ \ /
D E F
Algorithm: buildTree()
1) Pick an element from Preorder. Increment a Preorder Index Variable (preIndex in below
505
Chapter 78. Construct Tree from given Inorder and Preorder traversals
506
Chapter 78. Construct Tree from given Inorder and Preorder traversals
507
Chapter 78. Construct Tree from given Inorder and Preorder traversals
printInorder(node->right);
}
/* Driver program to test above functions */
int main()
{
char in[] = { 'D', 'B', 'E', 'A', 'F', 'C' };
char pre[] = { 'A', 'B', 'D', 'E', 'C', 'F' };
int len = sizeof(in) / sizeof(in[0]);
struct node* root = buildTree(in, pre, 0, len - 1);
/* Let us test the built tree by printing Insorder traversal */
printf("Inorder traversal of the constructed tree is \n");
printInorder(root);
getchar();
}
Java
508
Chapter 78. Construct Tree from given Inorder and Preorder traversals
509
Chapter 78. Construct Tree from given Inorder and Preorder traversals
// driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
char in[] = new char[] { 'D', 'B', 'E', 'A', 'F', 'C' };
char pre[] = new char[] { 'A', 'B', 'D', 'E', 'C', 'F' };
int len = in.length;
Node root = tree.buildTree(in, pre, 0, len - 1);
// building the tree by printing inorder traversal
System.out.println("Inorder traversal of constructed tree is : ");
tree.printInorder(root);
}
}
// This code has been contributed by Mayank Jaiswal
Python
510
Chapter 78. Construct Tree from given Inorder and Preorder traversals
511
Chapter 78. Construct Tree from given Inorder and Preorder traversals
Output :
Time Complexity: O(n^2). Worst case occurs when tree is left skewed. Example Preorder
and Inorder traversals for worst case are {A, B, C, D} and {D, C, B, A}.
Efficient Approach :
We can optimize the above solution using hashing (unordered_map in C++ or HashMap
in Java). We store indexes of inorder traversal in a hash table. So that search can be done
O(1) time.
C++
512
Chapter 78. Construct Tree from given Inorder and Preorder traversals
if (inStrt > inEnd)
return NULL;
/* Pick current node from Preorder traversal using preIndex
and increment preIndex */
int curr = pre[preIndex++];
struct Node* tNode = newNode(curr);
/* If this node has no children then return */
if (inStrt == inEnd)
return tNode;
/* Else find the index of this node in Inorder traversal */
int inIndex = mp[curr];
/* Using index in Inorder traversal, construct left and
right subtress */
tNode->left = buildTree(in, pre, inStrt, inIndex - 1, mp);
tNode->right = buildTree(in, pre, inIndex + 1, inEnd, mp);
return tNode;
}
// This function mainly creates an unordered_map, then
// calls buildTree()
struct Node* buldTreeWrap(char in[], char pre[], int len)
{
// Store indexes of all items so that we
// we can quickly find later
unordered_map<char, int> mp;
for (int i = 0; i < len; i++)
mp[in[i]] = i;
return buildTree(in, pre, 0, len - 1, mp);
}
/* This funtcion is here just to test buildTree() */
void printInorder(struct Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%c ", node->data);
printInorder(node->right);
}
/* Driver program to test above functions */
513
Chapter 78. Construct Tree from given Inorder and Preorder traversals
int main()
{
char in[] = { 'D', 'B', 'E', 'A', 'F', 'C' };
char pre[] = { 'A', 'B', 'D', 'E', 'C', 'F' };
int len = sizeof(in) / sizeof(in[0]);
struct Node* root = buldTreeWrap(in, pre, len);
/* Let us test the built tree by printing
Insorder traversal */
printf("Inorder traversal of the constructed tree is \n");
printInorder(root);
}
514
Chapter 78. Construct Tree from given Inorder and Preorder traversals
2. Keep popping the nodes from the stack until either the stack is empty, or the topmost
element of stack compares to the current element of InOrder traversal. Once the loop is
over, push the last node back into the stack and into the set.
3. Goto Step 1.
515
Chapter 78. Construct Tree from given Inorder and Preorder traversals
516
Chapter 78. Construct Tree from given Inorder and Preorder traversals
if (set.contains(stack.peek())) {
set.remove(stack.peek());
stack.pop().right = node;
}
else {
stack.peek().left = node;
}
}
stack.push(node);
} while (preorder[pre++] != inorder[in] && pre < preorder.length);
node = null;
while (!stack.isEmpty() && in < inorder.length && stack.peek().val == inorder[in]) {
node = stack.pop();
in++;
}
if (node != null) {
set.add(node);
stack.push(node);
}
}
return root;
}
// Function to print tree in Inorder
void printInorder(TreeNode node)
{
if (node == null)
return;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
System.out.print(node.val + " ");
/* now recur on right child */
printInorder(node.right);
}
// driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
int in[] = new int[] { 9, 8, 4, 2, 10, 5, 10, 1, 6, 3, 13, 12, 7 };
517
Chapter 78. Construct Tree from given Inorder and Preorder traversals
Output :
9 8 4 2 10 5 10 1 6 3 13 12 7
Source
https://www.geeksforgeeks.org/construct-tree-from-given-inorder-and-preorder-traversal/
518
Chapter 79
10
/ \
5 40
/ \ \
1 7 50
10
/ \
/ \
{1, 7, 5} {50, 40}
519
Chapter 79. Construct a Binary Search Tree from given postorder
We recursively follow above steps for subarrays {1, 7, 5} and {40, 50}, and get the complete
tree.
Method 2 ( O(n) time complexity )
The trick is to set a range {min .. max} for every node. Initialize the range as {INT_MIN
.. INT_MAX}. The last node will definitely be in range, so create root node. To construct
the left subtree, set the range as {INT_MIN …root->data}. If a values is in the range
{INT_MIN .. root->data}, the values is part part of left subtree. To construct the right
subtree, set the range as {root->data .. INT_MAX}.
Following code is used to generate the exact Binary Search Tree of a given post order
traversal.
C
520
Chapter 79. Construct a Binary Search Tree from given postorder
struct node* root = NULL;
// If current element of post[] is in range, then
// only it is part of current subtree
if (key > min && key < max)
{
// Allocate memory for root of this subtree and decrement
// *postIndex
root = newNode(key);
*postIndex = *postIndex - 1;
if (*postIndex >= 0)
{
// All nodes which are in range {key..max} will go in right
// subtree, and first such node will be root of right subtree.
root->right = constructTreeUtil(post, postIndex, post[*postIndex],
key, max, size );
// Contruct the subtree under root
// All nodes which are in range {min .. key} will go in left
// subtree, and first such node will be root of left subtree.
root->left = constructTreeUtil(post, postIndex, post[*postIndex],
min, key, size );
}
}
return root;
}
// The main function to construct BST from given postorder
// traversal. This function mainly uses constructTreeUtil()
struct node *constructTree (int post[], int size)
{
int postIndex = size-1;
return constructTreeUtil(post, &postIndex, post[postIndex],
INT_MIN, INT_MAX, size);
}
// A utility function to print inorder traversal of a Binary Tree
void printInorder (struct node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
521
Chapter 79. Construct a Binary Search Tree from given postorder
// Driver program to test above functions
int main ()
{
int post[] = {1, 7, 5, 50, 40, 10};
int size = sizeof(post) / sizeof(post[0]);
struct node *root = constructTree(post, size);
printf("Inorder traversal of the constructed tree: \n");
printInorder(root);
return 0;
}
Java
522
Chapter 79. Construct a Binary Search Tree from given postorder
523
Chapter 79. Construct a Binary Search Tree from given postorder
printInorder(node.left);
System.out.print(node.data + " ");
printInorder(node.right);
}
// Driver program to test above functions
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
int post[] = new int[]{1, 7, 5, 50, 40, 10};
int size = post.length;
Node root = tree.constructTree(post, size);
System.out.println("Inorder traversal of the constructed tree:");
tree.printInorder(root);
}
}
// This code has been contributed by Mayank Jaiswal
Output:
Note that the output to the program will always be a sorted sequence as we are printing the
inorder traversal of a Binary Search Tree.
Source
https://www.geeksforgeeks.org/construct-a-binary-search-tree-from-given-postorder/
524
Chapter 80
Input :
in[] = {2, 1, 3}
post[] = {2, 3, 1}
Input :
in[] = {4, 8, 2, 5, 1, 6, 3, 7}
post[] = {8, 4, 5, 2, 6, 7, 3, 1}
525
Chapter 80. Construct a Binary Tree from Postorder and Inorder
We have already discussed construction of tree from iven Inorder and Preorder traversals.
The idea is similar.
Let us see the process of constructing tree from in[] = {4, 8, 2, 5, 1, 6, 3, 7} and post[] =
{8, 4, 5, 2, 6, 7, 3, 1}
1) We first find the last node in post[]. The last node is “1”, we know this value is root as
root always appear in the end of postorder traversal.
2) We search “1” in in[] to find left and right subtrees of root. Everything on left of “1” in
in[] is in left subtree and everything on right is in right subtree.
1
/ \
[4, 8, 2, 5] [6, 3, 7]
C++
526
Chapter 80. Construct a Binary Tree from Postorder and Inorder
527
Chapter 80. Construct a Binary Tree from Postorder and Inorder
}
return i;
}
/* Helper function that allocates a new node */
Node* newNode(int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}
/* This funtcion is here just to test */
void preOrder(Node* node)
{
if (node == NULL)
return;
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
// Driver code
int main()
{
int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 };
int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 };
int n = sizeof(in) / sizeof(in[0]);
Node* root = buildTree(in, post, n);
cout << "Preorder of the constructed tree : \n";
preOrder(root);
return 0;
}
Java
528
Chapter 80. Construct a Binary Tree from Postorder and Inorder
public Node(int data)
{
this.data = data;
left = right = null;
}
}
// Class Index created to implement pass by reference of Index
class Index {
int index;
}
class BinaryTree {
/* Recursive function to construct binary of size n
from Inorder traversal in[] and Postrder traversal
post[]. Initial values of inStrt and inEnd should
be 0 and n -1. The function doesn't do any error
checking for cases where inorder and postorder
do not form a tree */
Node buildUtil(int in[], int post[], int inStrt,
int inEnd, Index pIndex)
{
// Base case
if (inStrt > inEnd)
return null;
/* Pick current node from Postrder traversal using
postIndex and decrement postIndex */
Node node = new Node(post[pIndex.index]);
(pIndex.index)--;
/* If this node has no children then return */
if (inStrt == inEnd)
return node;
/* Else find the index of this node in Inorder
traversal */
int iIndex = search(in, inStrt, inEnd, node.data);
/* Using index in Inorder traversal, construct left and
right subtress */
node.right = buildUtil(in, post, iIndex + 1, inEnd, pIndex);
node.left = buildUtil(in, post, inStrt, iIndex - 1, pIndex);
return node;
}
529
Chapter 80. Construct a Binary Tree from Postorder and Inorder
Output :
530
Chapter 80. Construct a Binary Tree from Postorder and Inorder
531
Chapter 80. Construct a Binary Tree from Postorder and Inorder
traversal */
int iIndex = mp[curr];
/* Using index in Inorder traversal, construct
left and right subtress */
node->right = buildUtil(in, post, iIndex + 1,
inEnd, pIndex, mp);
node->left = buildUtil(in, post, inStrt,
iIndex - 1, pIndex, mp);
return node;
}
// This function mainly creates an unordered_map, then
// calls buildTreeUtil()
struct Node* buildTree(int in[], int post[], int len)
{
// Store indexes of all items so that we
// we can quickly find later
unordered_map<int, int> mp;
for (int i = 0; i < len; i++)
mp[in[i]] = i;
int index = len - 1; // Index in postorder
return buildUtil(in, post, 0, len - 1,
&index, mp);
}
/* Helper function that allocates a new node */
Node* newNode(int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}
/* This funtcion is here just to test */
void preOrder(Node* node)
{
if (node == NULL)
return;
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
// Driver code
532
Chapter 80. Construct a Binary Tree from Postorder and Inorder
int main()
{
int in[] = { 4, 8, 2, 5, 1, 6, 3, 7 };
int post[] = { 8, 4, 5, 2, 6, 7, 3, 1 };
int n = sizeof(in) / sizeof(in[0]);
Node* root = buildTree(in, post, n);
cout << "Preorder of the constructed tree : \n";
preOrder(root);
return 0;
}
Source
https://www.geeksforgeeks.org/construct-a-binary-tree-from-postorder-and-inorder/
Time Complexity : O(n)
This article is contributed by Rishi. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
533
Chapter 81
Construct a complete binary tree from given array in level order fashion - GeeksforGeeks
Given an array of elements, our task is to construct a complete binary tree from this array
in level order fashion. That is, elements from left in the array will be filled in the tree level
wise starting from level 0.
Examples:
534
Chapter 81. Construct a complete binary tree from given array in level order fashion
If we observe carefully we can see that if parent node is at index i in the array then the left
child of that node is at index (2*i + 1) and right child is at index (2*i + 2) in the array.
Using this concept, we can easily insert the left and right nodes by choosing its parent node.
We will insert the first element present in the array as the root node at level 0 in the tree
and start traversing the array and for every node i we will insert its both childs left and
right in the tree.
Below is the recursive program to do this:
C++
535
Chapter 81. Construct a complete binary tree from given array in level order fashion
// insert right child
root->right = insertLevelOrder(arr,
root->right, 2 * i + 2, n);
}
return root;
}
// Function to print tree nodes in
// InOrder fashion
void inOrder(Node* root)
{
if (root != NULL)
{
inOrder(root->left);
cout << root->data <<" ";
inOrder(root->right);
}
}
// Driver program to test above function
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 6, 6, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
Node* root = insertLevelOrder(arr, root, 0, n);
inOrder(root);
}
// This code is contributed by Chhavi
Java
536
Chapter 81. Construct a complete binary tree from given array in level order fashion
}
}
// Function to insert nodes in level order
public Node insertLevelOrder(int[] arr, Node root,
int i)
{
// Base case for recursion
if (i < arr.length) {
Node temp = new Node(arr[i]);
root = temp;
// insert left child
root.left = insertLevelOrder(arr, root.left,
2 * i + 1);
// insert right child
root.right = insertLevelOrder(arr, root.right,
2 * i + 2);
}
return root;
}
// Function to print tree nodes in InOrder fashion
public void inOrder(Node root)
{
if (root != null) {
inOrder(root.left);
System.out.print(root.data + " ");
inOrder(root.right);
}
}
// Driver program to test above function
public static void main(String args[])
{
Tree t2 = new Tree();
int arr[] = { 1, 2, 3, 4, 5, 6, 6, 6, 6 };
t2.root = t2.insertLevelOrder(arr, t2.root, 0);
t2.inOrder(t2.root);
}
}
Output:
6 4 6 2 5 1 6 3 6
537
Chapter 81. Construct a complete binary tree from given array in level order fashion
Time Complexity: O(n), where n is the total number of nodes in the tree.
Source
https://www.geeksforgeeks.org/construct-complete-binary-tree-given-array/
538
Chapter 82
Input: pre[] = {10, 30, 20, 5, 15}, preLN[] = {'N', 'N', 'L', 'L', 'L'}
Output: Root of following tree
10
/ \
30 15
/ \
20 5
The first element in pre[] will always be root. So we can easily figure out root. If left
subtree is empty, the right subtree must also be empty and preLN[] entry for root must be
‘L’. We can simply create a node and return it. If left and right subtrees are not empty, then
recursively call for left and right subtrees and link the returned nodes to root.
C
539
Chapter 82. Construct a special tree from given preorder traversal
540
Chapter 82. Construct a special tree from given preorder traversal
541
Chapter 82. Construct a special tree from given preorder traversal
Java
542
Chapter 82. Construct a special tree from given preorder traversal
543
Chapter 82. Construct a special tree from given preorder traversal
Output:
Source
https://www.geeksforgeeks.org/construct-a-special-tree-from-given-preorder-traversal/
544
Chapter 83
Construct a tree from Inorder and Level order traversals | Set 1 - GeeksforGeeks
Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Fol-
lowing is an example to illustrate the problem.
545
Chapter 83. Construct a tree from Inorder and Level order traversals | Set 1
20
/ \
/ \
{4,8,10,12,14} {22}
Let us call {4,8,10,12,14} as left subarray in Inorder traversal and {22} as right subarray in
Inorder traversal.
In level order traversal, keys of left and right subtrees are not consecutive. So we extract all
nodes from level order traversal which are in left subarray of Inorder traversal. To construct
the left subtree of root, we recur for the extracted elements from level order traversal and
left subarray of inorder traversal. In the above example, we recur for following two arrays.
Similarly, we recur for following two arrays and construct the right subtree.
546
Chapter 83. Construct a tree from Inorder and Level order traversals | Set 1
547
Chapter 83. Construct a tree from Inorder and Level order traversals | Set 1
{
// If start index is more than the end index
if (inStrt > inEnd)
return NULL;
/* The first node in level order traversal is root */
Node *root = newNode(level[0]);
/* If this node has no children then return */
if (inStrt == inEnd)
return root;
/* Else find the index of this node in Inorder traversal */
int inIndex = search(in, inStrt, inEnd, root->key);
// Extract left subtree keys from level order traversal
int *llevel = extrackKeys(in, level, inIndex, n);
// Extract right subtree keys from level order traversal
int *rlevel = extrackKeys(in + inIndex + 1, level, n-inIndex-1, n);
/* construct left and right subtress */
root->left = buildTree(in, llevel, inStrt, inIndex-1, n);
root->right = buildTree(in, rlevel, inIndex+1, inEnd, n);
// Free memory to avoid memory leak
delete [] llevel;
delete [] rlevel;
return root;
}
/* Uti;ity function to print inorder traversal of binary tree */
void printInorder(Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
cout << node->key << " ";
printInorder(node->right);
}
/* Driver program to test above functions */
int main()
{
int in[] = {4, 8, 10, 12, 14, 20, 22};
int level[] = {20, 8, 22, 4, 12, 10, 14};
548
Chapter 83. Construct a tree from Inorder and Level order traversals | Set 1
int n = sizeof(in)/sizeof(in[0]);
Node *root = buildTree(in, level, 0, n - 1, n);
/* Let us test the built tree by printing Insorder traversal */
cout << "Inorder traversal of the constructed tree is \n";
printInorder(root);
return 0;
}
Java
549
Chapter 83. Construct a tree from Inorder and Level order traversals | Set 1
550
Chapter 83. Construct a tree from Inorder and Level order traversals | Set 1
printInorder(node.left);
System.out.print(node.data + " ");
printInorder(node.right);
}
// Driver program to test the above functions
public static void main(String args[])
{
Tree tree = new Tree();
int in[] = new int[]{4, 8, 10, 12, 14, 20, 22};
int level[] = new int[]{20, 8, 22, 4, 12, 10, 14};
int n = in.length;
Node node = tree.buildTree(in, level);
/* Let us test the built tree by printing Inorder traversal */
System.out.print("Inorder traversal of the constructed tree is ");
tree.printInorder(node);
}
}
// This code has been contributed by Mayank Jaiswal
Python3
551
Chapter 83. Construct a tree from Inorder and Level order traversals | Set 1
552
Chapter 83. Construct a tree from Inorder and Level order traversals | Set 1
Output:
An upper bound on time complexity of above method is O(n3 ). In the main recursive
function, extractNodes() is called which takes O(n2 ) time.
The code can be optimized in many ways and there may be better solutions.
Construct a tree from Inorder and Level order traversals | Set 2
This article is contributed by Abhay Rathi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/construct-tree-inorder-level-order-traversals/
553
Chapter 84
Construct a tree from Inorder and Level order traversals | Set 2 - GeeksforGeeks
Given inorder and level-order traversals of a Binary Tree, construct the Binary Tree. Fol-
lowing is an example to illustrate the problem.
Examples:
554
Chapter 84. Construct a tree from Inorder and Level order traversals | Set 2
If it is the part of left subtree then add in one lLevel arrray for left other wise add it to
rLevel array for right subtree.
Below is the c++ implementation with the above idea
555
Chapter 84. Construct a tree from Inorder and Level order traversals | Set 2
// Separate level order traversals
// of left and right subtrees.
int lLevel[s.size()]; // Left
int rLevel[iEnd-iStart-s.size()]; // Right
int li = 0, ri = 0;
for (int i=1;i<n;i++) {
if (s.find(levelOrder[i]) != s.end())
lLevel[li++] = levelOrder[i];
else
rLevel[ri++] = levelOrder[i];
}
// Recursively build left and right
// subtrees and return root.
root->left = buildTree(inorder, lLevel,
iStart, index-1, index-iStart);
root->right = buildTree(inorder, rLevel,
index+1, iEnd, iEnd-index);
return root;
}
/* Utility function to print inorder
traversal of binary tree */
void printInorder(Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
cout << node->key << " ";
printInorder(node->right);
}
// Driver Code
int main()
{
int in[] = {4, 8, 10, 12, 14, 20, 22};
int level[] = {20, 8, 22, 4, 12, 10, 14};
int n = sizeof(in)/sizeof(in[0]);
Node *root = buildTree(in, level, 0,
n - 1, n);
/* Let us test the built tree by
printing Insorder traversal */
cout << "Inorder traversal of the "
"constructed tree is \n";
printInorder(root);
556
Chapter 84. Construct a tree from Inorder and Level order traversals | Set 2
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/construct-tree-inorder-level-order-traversals-set-2/
557
Chapter 85
Construct the full k-ary tree from its preorder traversal - GeeksforGeeks
Given an array which contains the preorder traversal of full k-ary tree, construct the full
k-ary tree and print its postorder traversal. A full k-ary tree is a tree where each node has
either 0 or k children.
Examples:
558
Chapter 85. Construct the full k-ary tree from its preorder traversal
559
Chapter 85. Construct the full k-ary tree from its preorder traversal
Output:
560
Chapter 85. Construct the full k-ary tree from its preorder traversal
Source
https://www.geeksforgeeks.org/construct-full-k-ary-tree-preorder-traversal/
561
Chapter 86
mat[i][j] = 1 if i is ancestor of j
mat[i][j] = 0, otherwise
Construct a Binary Tree from given ancestor matrix where all its values of nodes are from
0 to n-1.
1. It may be assumed that the input provided the program is valid and tree can be
constructed out of it.
2. Many Binary trees can be constructed from one input. The program will construct
any one of them.
Examples:
Input: 0 1 1
0 0 0
0 0 0
Output: Root of one of the below trees.
0 0
/ \ OR / \
1 2 2 1
Input: 0 0 0 0 0 0
562
Chapter 86. Construct tree from ancestor matrix
1 0 0 0 1 0
0 0 0 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0
1 1 1 1 1 0
Output: Root of one of the below trees.
5 5 5
/ \ / \ / \
1 2 OR 2 1 OR 1 2 OR ....
/ \ / / / \ / \ /
0 4 3 3 0 4 4 0 3
There are different possible outputs because ancestor
matrix doesn't store that which child is left and which
is right.
563
Chapter 86. Construct tree from ancestor matrix
564
Chapter 86. Construct tree from ancestor matrix
node[it->second] = newNode(it->second);
// To store last processed node. This node will be
// root after loop terminates
root = node[it->second];
// if non-leaf node
if (it->first != 0)
{
// traverse row 'it->second' in the matrix
for (int i = 0; i < N; i++)
{
// if parent is not set and ancestor exits
if (!parent[i] && mat[it->second][i])
{
// check for unoccupied left/right node
// and set parent of node i
if (!node[it->second]->left)
node[it->second]->left = node[i];
else
node[it->second]->right = node[i];
parent[i] = 1;
}
}
}
}
return root;
}
/* Given a binary tree, print its nodes in inorder */
void printInorder(Node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
// Driver program
int main()
{
int mat[N][N] = {{ 0, 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1, 0 },
{ 0, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0 },
565
Chapter 86. Construct tree from ancestor matrix
{ 1, 1, 1, 1, 1, 0 }
};
Node* root = ancestorTree(mat);
cout << "Inorder traversal of tree is \n";
printInorder(root);
return 0;
}
Output:
Note that we can also use an array of vectors in place of multimap. We have used multimap
for simplicity. Array of vectors would improve performance as inserting and accessing ele-
ments would take O(1) time.
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/construct-tree-from-ancestor-matrix/
566
Chapter 87
Continuous Tree
Input : 3
/ \
2 4
/ \ \
1 3 5
Output: "Yes"
Input : 7
/ \
5 8
/ \ \
6 4 10
Output: "No"
The solution requires a traversal of tree. The important things to check are to make sure
that all corner cases are handled. The corner cases include, empty tree, single node tree, a
node with only left child and a node with only right child.
567
Chapter 87. Continuous Tree
In tree traversal, we recursively check if left and right subtree are continuous. We also check
if difference between keys of current node’s key and its children keys is 1. Below is C++
implementation of the idea.
568
Chapter 87. Continuous Tree
// If both left and right subtrees are not empty, check
// everything
return abs(ptr->data - ptr->left->data)==1 &&
abs(ptr->data - ptr->right->data)==1 &&
treeContinuous(ptr->left) &&
treeContinuous(ptr->right);
}
/* Driver program to test mirror() */
int main()
{
struct Node *root = newNode(3);
root->left = newNode(2);
root->right = newNode(4);
root->left->left = newNode(1);
root->left->right = newNode(3);
root->right->right = newNode(5);
treeContinuous(root)? cout << "Yes" : cout << "No";
return 0;
}
Output:
Yes
Source
https://www.geeksforgeeks.org/continuous-tree/
569
Chapter 88
570
Chapter 88. Convert Ternary Expression to a Binary Tree
C++
571
Chapter 88. Convert Ternary Expression to a Binary Tree
Java
572
Chapter 88. Convert Ternary Expression to a Binary Tree
573
Chapter 88. Convert Ternary Expression to a Binary Tree
}
}
/* This code is contributed by Mr. Somesh Awasthi */
Python3
574
Chapter 88. Convert Ternary Expression to a Binary Tree
def print_tree(root):
if not root:
return
print(root.data, end=' ')
print_tree(root.left)
print_tree(root.right)
# Driver Code
if __name__ == "__main__":
string_expression = "a?b?c:d:e"
root_node = convert_expression(string_expression, 0)
print_tree(root_node)
# This code is contributed
# by Kanav Malhotra
Output :
a b c d e
Source
https://www.geeksforgeeks.org/convert-ternary-expression-binary-tree/
575
Chapter 89
Convert a Binary Tree into Doubly Linked List in spiral fashion - GeeksforGeeks
Given a Binary Tree, convert it into Doubly Linked List where the nodes are represented
Spirally. The left pointer of the binary tree node should act as a previous node for created
DLL and right pointer should act as next node.
The solution should not allocate extra memory for DLL nodes. It should use binary tree
nodes for creating DLL i.e. only change of pointers is allowed
576
Chapter 89. Convert a Binary Tree into Doubly Linked List in spiral fashion
For example, for the tree on left side, Doubly Linked List can be,
1 2 3 7 6 5 4 8 9 10 11 13 14 or
1 3 2 4 5 6 7 14 13 11 10 9 8.
We strongly recommend you to minimize your browser and try this yourself
first.
We can do this by doing a spiral order traversal in O(n) time and O(n) extra space. The
idea is to use deque (Double-ended queue) that can be expanded or contracted on both
ends (either its front or its back). We do something similar to level order traversal but to
maintain spiral order, for every odd level, we dequeue node from the front and inserts its
left and right children in the back of the deque data structure. And for each even level, we
dequeue node from the back and inserts its right and left children in the front of deque. We
also maintain a stack to store Binary Tree nodes. Whenever we pop nodes from deque, we
push that node into stack. Later, we pop all nodes from stack and push the nodes in the
beginning of the list. We can avoid use of stack if we maintain a tail pointer that always
points to last node of DLL and inserts nodes in O(1) time in the end.
Below is C++ implementation of above idea
C++
577
Chapter 89. Convert a Binary Tree into Doubly Linked List in spiral fashion
(*head_ref)->left = node ;
// move the head to point to the given node
(*head_ref) = node;
}
// Function to prints contents of DLL
void printList(Node *node)
{
while (node != NULL)
{
cout << node->data << " ";
node = node->right;
}
}
/* Function to print corner node at each level */
void spiralLevelOrder(Node *root)
{
// Base Case
if (root == NULL)
return;
// Create an empty deque for doing spiral
// level order traversal and enqueue root
deque<Node*> q;
q.push_front(root);
// create a stack to store Binary Tree nodes
// to insert into DLL later
stack<Node*> stk;
int level = 0;
while (!q.empty())
{
// nodeCount indicates number of Nodes
// at current level.
int nodeCount = q.size();
// Dequeue all Nodes of current level and
// Enqueue all Nodes of next level
if (level&1) //odd level
{
while (nodeCount > 0)
{
// dequeue node from front & push it to
// stack
Node *node = q.front();
578
Chapter 89. Convert a Binary Tree into Doubly Linked List in spiral fashion
q.pop_front();
stk.push(node);
// insert its left and right children
// in the back of the deque
if (node->left != NULL)
q.push_back(node->left);
if (node->right != NULL)
q.push_back(node->right);
nodeCount--;
}
}
else //even level
{
while (nodeCount > 0)
{
// dequeue node from the back & push it
// to stack
Node *node = q.back();
q.pop_back();
stk.push(node);
// inserts its right and left children
// in the front of the deque
if (node->right != NULL)
q.push_front(node->right);
if (node->left != NULL)
q.push_front(node->left);
nodeCount--;
}
}
level++;
}
// head pointer for DLL
Node* head = NULL;
// pop all nodes from stack and
// push them in the beginning of the list
while (!stk.empty())
{
push(&head, stk.top());
stk.pop();
}
cout << "Created DLL is:\n";
printList(head);
579
Chapter 89. Convert a Binary Tree into Doubly Linked List in spiral fashion
}
// Utility function to create a new tree Node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in above diagram
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->left->left->right = newNode(9);
root->left->right->left = newNode(10);
root->left->right->right = newNode(11);
//root->right->left->left = newNode(12);
root->right->left->right = newNode(13);
root->right->right->left = newNode(14);
//root->right->right->right = newNode(15);
spiralLevelOrder(root);
return 0;
}
Java
580
Chapter 89. Convert a Binary Tree into Doubly Linked List in spiral fashion
int data;
Node left, right;
public Node(int data)
{
this.data = data;
left = right = null;
}
}
class BinaryTree
{
Node root;
Node head;
/* Given a reference to a node,
inserts the node on the front of the list. */
void push(Node node)
{
// Make right of given node as head and left as
// NULL
node.right = head;
node.left = null;
// change left of head node to given node
if (head != null)
head.left = node;
// move the head to point to the given node
head = node;
}
// Function to prints contents of DLL
void printList(Node node)
{
while (node != null)
{
System.out.print(node.data + " ");
node = node.right;
}
}
/* Function to print corner node at each level */
void spiralLevelOrder(Node root)
{
// Base Case
if (root == null)
return;
581
Chapter 89. Convert a Binary Tree into Doubly Linked List in spiral fashion
// Create an empty deque for doing spiral
// level order traversal and enqueue root
Deque<Node> q = new LinkedList<Node>();
q.addFirst(root);
// create a stack to store Binary Tree nodes
// to insert into DLL later
Stack<Node> stk = new Stack<Node>();
int level = 0;
while (!q.isEmpty())
{
// nodeCount indicates number of Nodes
// at current level.
int nodeCount = q.size();
// Dequeue all Nodes of current level and
// Enqueue all Nodes of next level
if ((level & 1) %2 != 0) //odd level
{
while (nodeCount > 0)
{
// dequeue node from front & push it to
// stack
Node node = q.peekFirst();
q.pollFirst();
stk.push(node);
// insert its left and right children
// in the back of the deque
if (node.left != null)
q.addLast(node.left);
if (node.right != null)
q.addLast(node.right);
nodeCount--;
}
}
else //even level
{
while (nodeCount > 0)
{
// dequeue node from the back & push it
// to stack
Node node = q.peekLast();
q.pollLast();
stk.push(node);
582
Chapter 89. Convert a Binary Tree into Doubly Linked List in spiral fashion
// inserts its right and left children
// in the front of the deque
if (node.right != null)
q.addFirst(node.right);
if (node.left != null)
q.addFirst(node.left);
nodeCount--;
}
}
level++;
}
// pop all nodes from stack and
// push them in the beginning of the list
while (!stk.empty())
{
push(stk.peek());
stk.pop();
}
System.out.println("Created DLL is : ");
printList(head);
}
// Driver program to test above functions
public static void main(String[] args)
{
// Let us create binary tree as shown in above diagram
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.left.left.left = new Node(8);
tree.root.left.left.right = new Node(9);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(11);
// tree.root.right.left.left = new Node(12);
tree.root.right.left.right = new Node(13);
tree.root.right.right.left = new Node(14);
// tree.root.right.right.right = new Node(15);
tree.spiralLevelOrder(tree.root);
583
Chapter 89. Convert a Binary Tree into Doubly Linked List in spiral fashion
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output :
Source
https://www.geeksforgeeks.org/convert-a-binary-tree-into-doubly-linked-list-in-spiral-fashion/
584
Chapter 90
Method 1 (Recursive)
Algorithm – Mirror(tree):
585
Chapter 90. Convert a Binary Tree into its Mirror Tree
586
Chapter 90. Convert a Binary Tree into its Mirror Tree
587
Chapter 90. Convert a Binary Tree into its Mirror Tree
Java
588
Chapter 90. Convert a Binary Tree into its Mirror Tree
return node;
}
void inOrder()
{
inOrder(root);
}
/* Helper function to test mirror(). Given a binary
search tree, print out its data elements in
increasing sorted order.*/
void inOrder(Node node)
{
if (node == null)
return;
inOrder(node.left);
System.out.print(node.data + " ");
inOrder(node.right);
}
/* testing for example nodes */
public static void main(String args[])
{
/* creating a binary tree and entering the nodes */
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
/* print inorder traversal of the input tree */
System.out.println("Inorder traversal of input tree is :");
tree.inOrder();
System.out.println("");
/* convert tree to its mirror */
tree.mirror();
/* print inorder traversal of the minor tree */
System.out.println("Inorder traversal of binary tree is : ");
tree.inOrder();
}
}
589
Chapter 90. Convert a Binary Tree into its Mirror Tree
Output :
Time & Space Complexities: This program is similar to traversal of tree space and time
complexities will be same as Tree traversal (Please see our Tree Traversal post for details)
Method 2 (Iterative)
The idea is to do queue based level order traversal. While doing traversal, swap left and
right children of every node.
590
Chapter 90. Convert a Binary Tree into its Mirror Tree
/ \
2 5
/ \
1 3
is changed to...
4
/ \
5 2
/ \
3 1
*/
void mirror(Node* root)
{
if (root == NULL)
return;
queue<Node*> q;
q.push(root);
// Do BFS. While doing BFS, keep swapping
// left and right children
while (!q.empty())
{
// pop top node from queue
Node* curr = q.front();
q.pop();
// swap left child with right child
swap(curr->left, curr->right);
// push left and right children
if (curr->left)
q.push(curr->left);
if (curr->right)
q.push(curr->right);
}
}
/* Helper function to print Inorder traversal.*/
void inOrder(struct Node* node)
{
if (node == NULL)
return;
inOrder(node->left);
cout << node->data << " ";
inOrder(node->right);
591
Chapter 90. Convert a Binary Tree into its Mirror Tree
}
/* Driver program to test mirror() */
int main()
{
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
/* Print inorder traversal of the input tree */
cout << "\n Inorder traversal of the"
" constructed tree is \n";
inOrder(root);
/* Convert tree to its mirror */
mirror(root);
/* Print inorder traversal of the mirror tree */
cout << "\n Inorder traversal of the "
"mirror tree is \n";
inOrder(root);
return 0;
}
Source
https://www.geeksforgeeks.org/write-an-efficient-c-function-to-convert-a-tree-into-its-mirror-tree/
592
Chapter 91
Convert a Binary Tree such that every node stores the sum of all nodes in its right subtree
- GeeksforGeeks
Given a binary tree, change the value in each node to sum of all the values in the nodes in
the right subtree including its own.
Examples:
Input :
1
/ \
2 3
Output :
4
/ \
2 3
Input :
1
/ \
2 3
/ \ \
4 5 6
Output :
10
/ \
7 9
593
Chapter 91. Convert a Binary Tree such that every node stores the sum of all nodes in its
right subtree
/ \ \
4 5 6
Approach : The idea is to traverse the given binary tree in bottom up manner. Recur-
sively compute the sum of nodes in right and left subtrees. Accumulate sum of nodes in the
right subtree to the current node and return sum of nodes under current subtree.
Below is the implementation of above approach.
594
Chapter 91. Convert a Binary Tree such that every node stores the sum of all nodes in its
right subtree
// Return sum of values under root
return root->data + leftsum;
}
// Function to traverse tree in inorder way
void inorder(struct Node* node)
{
if (node == NULL)
return;
inorder(node->left);
cout << node->data << " ";
inorder(node->right);
}
// Driver code
int main()
{
/* Let us construct a binary tree
1
/ \
2 3
/ \ \
4 5 6 */
struct Node* root = NULL;
root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->right = createNode(6);
// new tree construction
updateBTree(root);
cout << "Inorder traversal of the modified tree is \n";
inorder(root);
return 0;
}
Output:
595
Chapter 91. Convert a Binary Tree such that every node stores the sum of all nodes in its
right subtree
Source
https://www.geeksforgeeks.org/convert-a-binary-tree-such-that-every-node-stores-the-sum-of-all-nodes-in-its-right-
596
Chapter 92
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue) - GeeksforGeeks
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make
inorder traversal faster and do it without stack and without recursion. In a simple threaded
binary tree, the NULL right pointers are used to store inorder successor. Where-ever a right
pointer is NULL, it is used to store inorder successor.
Following diagram shows an example Single Threaded Binary Tree. The dotted lines repre-
sent threads.
struct Node
{
int key;
Node *left, *right;
// Used to indicate whether the right pointer is a normal right
597
Chapter 92. Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
598
Chapter 92. Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
createThreadedUtil(root->left, q);
q->pop();
if (root->right)
createThreadedUtil(root->right, q);
// If right pointer is NULL, link it to the
// inorder successor and set 'isThreaded' bit.
else
{
root->right = q->front();
root->isThreaded = true;
}
}
// This function uses populateQueue() and
// createThreadedUtil() to convert a given binary tree
// to threaded tree.
void createThreaded(Node *root)
{
// Create a queue to store inorder traversal
std::queue <Node *> q;
// Store inorder traversal in queue
populateQueue(root, &q);
// Link NULL right pointers to inorder successor
createThreadedUtil(root, &q);
}
// A utility function to find leftmost node in a binary
// tree rooted with 'root'. This function is used in inOrder()
Node *leftMost(Node *root)
{
while (root != NULL && root->left != NULL)
root = root->left;
return root;
}
// Function to do inorder traversal of a threadded binary tree
void inOrder(Node *root)
{
if (root == NULL) return;
// Find the leftmost node in Binary Tree
Node *cur = leftMost(root);
while (cur != NULL)
599
Chapter 92. Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
{
cout << cur->key << " ";
// If this Node is a thread Node, then go to
// inorder successor
if (cur->isThreaded)
cur = cur->right;
else // Else go to the leftmost child in right subtree
cur = leftMost(cur->right);
}
}
// A utility function to create a new node
Node *newNode(int key)
{
Node *temp = new Node;
temp->left = temp->right = NULL;
temp->key = key;
return temp;
}
// Driver program to test above functions
int main()
{
/* 1
/ \
2 3
/ \ / \
4 5 6 7 */
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
createThreaded(root);
cout << "Inorder traversal of creeated threaded tree is\n";
inOrder(root);
return 0;
}
Java
600
Chapter 92. Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
import java.util.LinkedList;
import java.util.Queue;
/* Class containing left and right child of current
node and key value*/
class Node
{
int data;
Node left, right;
// Used to indicate whether the right pointer is a normal
// right pointer or a pointer to inorder successor.
boolean isThreaded;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
// Helper function to put the Nodes in inorder into queue
void populateQueue(Node node, Queue<Node> q)
{
if (node == null)
return;
if (node.left != null)
populateQueue(node.left, q);
q.add(node);
if (node.right != null)
populateQueue(node.right, q);
}
// Function to traverse queue, and make tree threaded
void createThreadedUtil(Node node, Queue<Node> q)
{
if (node == null)
return;
if (node.left != null)
createThreadedUtil(node.left, q);
q.remove();
if (node.right != null)
601
Chapter 92. Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
createThreadedUtil(node.right, q);
// If right pointer is NULL, link it to the
// inorder successor and set 'isThreaded' bit.
else
{
node.right = q.peek();
node.isThreaded = true;
}
}
// This function uses populateQueue() and
// createThreadedUtil() to convert a given binary tree
// to threaded tree.
void createThreaded(Node node)
{
// Create a queue to store inorder traversal
Queue<Node> q = new LinkedList<Node>();
// Store inorder traversal in queue
populateQueue(node, q);
// Link NULL right pointers to inorder successor
createThreadedUtil(node, q);
}
// A utility function to find leftmost node in a binary
// tree rooted with 'root'. This function is used in inOrder()
Node leftMost(Node node)
{
while (node != null && node.left != null)
node = node.left;
return node;
}
// Function to do inorder traversal of a threadded binary tree
void inOrder(Node node)
{
if (node == null)
return;
// Find the leftmost node in Binary Tree
Node cur = leftMost(node);
while (cur != null)
{
System.out.print(" " + cur.data + " ");
602
Chapter 92. Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
Output:
Source
https://www.geeksforgeeks.org/convert-binary-tree-threaded-binary-tree-2/
603
Chapter 93
struct Node
{
int key;
Node *left, *right;
// Used to indicate whether the right pointer is a normal right
604
Chapter 93. Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
605
Chapter 93. Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
{
// Find predecessor of root (Rightmost
// child in left subtree)
Node* l = createThreaded(root->left);
// Link a thread from predecessor to
// root.
l->right = root;
l->isThreaded = true;
}
// If current node is rightmost child
if (root->right == NULL)
return root;
// Recur for right subtree.
return createThreaded(root->right);
}
// A utility function to find leftmost node
// in a binary tree rooted with 'root'.
// This function is used in inOrder()
Node *leftMost(Node *root)
{
while (root != NULL && root->left != NULL)
root = root->left;
return root;
}
// Function to do inorder traversal of a threadded
// binary tree
void inOrder(Node *root)
{
if (root == NULL) return;
// Find the leftmost node in Binary Tree
Node *cur = leftMost(root);
while (cur != NULL)
{
cout << cur->key << " ";
// If this Node is a thread Node, then go to
// inorder successor
if (cur->isThreaded)
cur = cur->right;
else // Else go to the leftmost child in right subtree
606
Chapter 93. Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
cur = leftMost(cur->right);
}
}
// A utility function to create a new node
Node *newNode(int key)
{
Node *temp = new Node;
temp->left = temp->right = NULL;
temp->key = key;
return temp;
}
// Driver program to test above functions
int main()
{
/* 1
/ \
2 3
/ \ / \
4 5 6 7 */
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
createThreaded(root);
cout << "Inorder traversal of creeated "
"threaded tree is\n";
inOrder(root);
return 0;
}
Output:
This algorithm works in O(n) time complexity and O(1) space other than function call stack.
Source
https://www.geeksforgeeks.org/convert-binary-tree-threaded-binary-tree-set-2-efficient/
607
Chapter 94
• The left and right pointers in nodes are to be used as previous and next pointers
respectively in converted Circular Linked List.
• The order of nodes in List must be same as Inorder of the given Binary Tree.
• The first node of Inorder traversal must be head node of the Circular List.
Example:
608
Chapter 94. Convert a Binary Tree to a Circular Doubly Link List
609
Chapter 94. Convert a Binary Tree to a Circular Doubly Link List
• Get the last node of the left list. Retrieving the last node is an O(1) operation, since
the prev pointer of the head points to the last node of the list.
• Connect it with the first node of the right list
• Get the last node of the second list
• Connect it with the head of the list.
610
Chapter 94. Convert a Binary Tree to a Circular Doubly Link List
leftList->left = rightLast;
// Right of last node refers to the first
// node of the List
rightLast->right = leftList;
return leftList;
}
// Function converts a tree to a circular Linked List
// and then returns the head of the Linked List
Node *bTreeToCList(Node *root)
{
if (root == NULL)
return NULL;
// Recursively convert left and right subtrees
Node *left = bTreeToCList(root->left);
Node *right = bTreeToCList(root->right);
// Make a circular linked list of single node
// (or root). To do so, make the right and
// left pointers of this node point to itself
root->left = root->right = root;
// Step 1 (concatenate the left list with the list
// with single node, i.e., current node)
// Step 2 (concatenate the returned list with the
// right List)
return concatenate(concatenate(left, root), right);
}
// Display Circular Link List
void displayCList(Node *head)
{
cout << "Circular Linked List is :\n";
Node *itr = head;
do
{
cout << itr->data <<" ";
itr = itr->right;
} while (head!=itr);
cout << "\n";
}
// Create a new Node and return its address
Node *newNode(int data)
611
Chapter 94. Convert a Binary Tree to a Circular Doubly Link List
{
Node *temp = new Node();
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver Program to test above function
int main()
{
Node *root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
Node *head = bTreeToCList(root);
displayCList(head);
return 0;
}
Java
612
Chapter 94. Convert a Binary Tree to a Circular Doubly Link List
}
// concatenate both the lists and returns the head
// of the List
public Node concatenate(Node leftList,Node rightList)
{
// If either of the list is empty, then
// return the other list
if (leftList == null)
return rightList;
if (rightList == null)
return leftList;
// Store the last Node of left List
Node leftLast = leftList.left;
// Store the last Node of right List
Node rightLast = rightList.left;
// Connect the last node of Left List
// with the first Node of the right List
leftLast.right = rightList;
rightList.left = leftLast;
// left of first node refers to
// the last node in the list
leftList.left = rightLast;
// Right of last node refers to the first
// node of the List
rightLast.right = leftList;
// Return the Head of the List
return leftList;
}
// Method converts a tree to a circular
// Link List and then returns the head
// of the Link List
public Node bTreeToCList(Node root)
{
if (root == null)
return null;
// Recursively convert left and right subtrees
Node left = bTreeToCList(root.left);
Node right = bTreeToCList(root.right);
613
Chapter 94. Convert a Binary Tree to a Circular Doubly Link List
614
Chapter 94. Convert a Binary Tree to a Circular Doubly Link List
Output:
Source
https://www.geeksforgeeks.org/convert-a-binary-tree-to-a-circular-doubly-link-list/
615
Chapter 95
I came across this interview during one of my interviews. A similar problem is discussed
in this post. The problem here is simpler as we don’t need to create circular DLL, but a
simple DLL. The idea behind its solution is quite simple and straight.
1. If left subtree exists, process the left subtree
…..1.a) Recursively convert the left subtree to DLL.
…..1.b) Then find inorder predecessor of root in left subtree (inorder predecessor is rightmost
node in left subtree).
616
Chapter 95. Convert a given Binary Tree to Doubly Linked List | Set 1
…..1.c) Make inorder predecessor as previous of root and root as next of inorder predecessor.
2. If right subtree exists, process the right subtree (Below 3 steps are similar to left subtree).
…..2.a) Recursively convert the right subtree to DLL.
…..2.b) Then find inorder successor of root in right subtree (inorder successor is leftmost
node in right subtree).
…..2.c) Make inorder successor as next of root and root as previous of inorder successor.
3. Find the leftmost node and return it (the leftmost node is always head of converted
DLL).
Below is the source code for above algorithm.
C
617
Chapter 95. Convert a given Binary Tree to Doubly Linked List | Set 1
618
Chapter 95. Convert a given Binary Tree to Doubly Linked List | Set 1
}
/* Function to print nodes in a given doubly linked list */
void printList(node *node)
{
while (node!=NULL)
{
printf("%d ", node->data);
node = node->right;
}
}
/* Driver program to test above functions*/
int main()
{
// Let us create the tree shown in above diagram
node *root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
// Convert to DLL
node *head = bintree2list(root);
// Print the converted list
printList(head);
return 0;
}
Java
619
Chapter 95. Convert a given Binary Tree to Doubly Linked List | Set 1
class BinaryTree
{
Node root;
/* This is the core function to convert Tree to list. This function
follows steps 1 and 2 of the above algorithm */
Node bintree2listUtil(Node node)
{
// Base case
if (node == null)
return node;
// Convert the left subtree and link to root
if (node.left != null)
{
// Convert the left subtree
Node left = bintree2listUtil(node.left);
// Find inorder predecessor. After this loop, left
// will point to the inorder predecessor
for (; left.right != null; left = left.right);
// Make root as next of the predecessor
left.right = node;
// Make predecssor as previous of root
node.left = left;
}
// Convert the right subtree and link to root
if (node.right != null)
{
// Convert the right subtree
Node right = bintree2listUtil(node.right);
// Find inorder successor. After this loop, right
// will point to the inorder successor
for (; right.left != null; right = right.left);
// Make root as previous of successor
right.left = node;
// Make successor as next of root
node.right = right;
}
return node;
620
Chapter 95. Convert a given Binary Tree to Doubly Linked List | Set 1
}
// The main function that first calls bintree2listUtil(), then follows
// step 3 of the above algorithm
Node bintree2list(Node node)
{
// Base case
if (node == null)
return node;
// Convert to DLL using bintree2listUtil()
node = bintree2listUtil(node);
// bintree2listUtil() returns root node of the converted
// DLL. We need pointer to the leftmost node which is
// head of the constructed DLL, so move to the leftmost node
while (node.left != null)
node = node.left;
return node;
}
/* Function to print nodes in a given doubly linked list */
void printList(Node node)
{
while (node != null)
{
System.out.print(node.data + " ");
node = node.right;
}
}
/* Driver program to test above functions*/
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
// Let us create the tree shown in above diagram
tree.root = new Node(10);
tree.root.left = new Node(12);
tree.root.right = new Node(15);
tree.root.left.left = new Node(25);
tree.root.left.right = new Node(30);
tree.root.right.left = new Node(36);
// Convert to DLL
Node head = tree.bintree2list(tree.root);
621
Chapter 95. Convert a given Binary Tree to Doubly Linked List | Set 1
// Print the converted list
tree.printList(head);
}
}
Python
622
Chapter 95. Convert a given Binary Tree to Doubly Linked List | Set 1
# Convert the right subtree
# and link to root
if root.right:
# Convert the right subtree
right = BTToDLLUtil(root.right)
# Find inorder successor, After
# this loop, right will point to
# the inorder successor of root
while right.left:
right = right.left
# Make root as previous
# of successor
right.left = root
# Make successor as
# next of root
root.right = right
return root
def BTToDLL(root):
if root is None:
return root
# Convert to doubly linked
# list using BLLToDLLUtil
root = BTToDLLUtil(root)
# We need pointer to left most
# node which is head of the
# constructed Doubly Linked list
while root.left:
root = root.left
return root
def print_list(head):
"""Function to print the given
doubly linked list"""
if head is None:
return
while head:
print(head.data, end = " ")
623
Chapter 95. Convert a given Binary Tree to Doubly Linked List | Set 1
head = head.right
# Driver Code
if __name__ == '__main__':
root = Node(10)
root.left = Node(12)
root.right = Node(15)
root.left.left = Node(25)
root.left.right = Node(30)
root.right.left = Node(36)
head = BTToDLL(root)
print_list(head)
# This code is contributed
# by viveksyngh
Output:
25 12 30 10 36 15
This article is compiled by Ashish Mangla and reviewed by GeeksforGeeks team. Please
write comments if you find anything incorrect, or you want to share more information about
the topic discussed above.
You may also like to see Convert a given Binary Tree to Doubly Linked List | Set 2 for
another simple and efficient solution.
Improved By : viveksyngh
Source
https://www.geeksforgeeks.org/in-place-convert-a-given-binary-tree-to-doubly-linked-list/
624
Chapter 96
625
Chapter 96. Convert a given Binary Tree to Doubly Linked List | Set 2
2) Fix Right Pointers: The above is intuitive and simple. How to change right pointers
to point to next node in DLL? The idea is to use left pointers fixed in step 1. We start
from the rightmost node in Binary Tree (BT). The rightmost node is the last node in DLL.
Since left pointers are changed to point to previous node in DLL, we can linearly traverse
the complete DLL using these pointers. The traversal would be from last to first node.
While traversing the DLL, we keep track of the previously visited node and change the right
pointer to the previous node. See fixNextPtr() in below implementation.
C
626
Chapter 96. Convert a given Binary Tree to Doubly Linked List | Set 2
{
fixPrevPtr(root->left);
root->left = pre;
pre = root;
fixPrevPtr(root->right);
}
}
// Changes right pointers to work as next pointers in converted DLL
struct node *fixNextPtr(struct node *root)
{
struct node *prev = NULL;
// Find the right most node in BT or last node in DLL
while (root && root->right != NULL)
root = root->right;
// Start from the rightmost node, traverse back using left pointers.
// While traversing, change right pointer of nodes.
while (root && root->left != NULL)
{
prev = root;
root = root->left;
root->right = prev;
}
// The leftmost node is head of linked list, return it
return (root);
}
// The main function that converts BST to DLL and returns head of DLL
struct node *BTToDLL(struct node *root)
{
// Set the previous pointer
fixPrevPtr(root);
// Set the next pointer and return head of DLL
return fixNextPtr(root);
}
// Traverses the DLL from left tor right
void printList(struct node *root)
{
while (root != NULL)
{
printf("\t%d", root->data);
root = root->right;
}
627
Chapter 96. Convert a given Binary Tree to Doubly Linked List | Set 2
}
// Driver program to test above functions
int main(void)
{
// Let us create the tree shown in above diagram
struct node *root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
printf("\n\t\tInorder Tree Traversal\n\n");
inorder(root);
struct node *head = BTToDLL(root);
printf("\n\n\t\tDLL Traversal\n\n");
printList(head);
return 0;
}
Java
628
Chapter 96. Convert a given Binary Tree to Doubly Linked List | Set 2
629
Chapter 96. Convert a given Binary Tree to Doubly Linked List | Set 2
{
while (root != null)
{
System.out.print(root.data + " ");
root = root.right;
}
}
// Standard Inorder traversal of tree
static void inorder(node root)
{
if (root == null)
return;
inorder(root.left);
System.out.print(root.data + " ");
inorder(root.right);
}
public static void main(String[] args)
{
// Let us create the tree shown in above diagram
node root = new node(10);
root.left = new node(12);
root.right = new node(15);
root.left.left = new node(25);
root.left.right = new node(30);
root.right.left = new node(36);
System.out.println("Inorder Tree Traversal");
inorder(root);
node head = BTTtoDLL(root);
System.out.println("\nDLL Traversal");
printlist(head);
}
}
// This code is contributed by Rishabh Mahrsee
Python
630
Chapter 96. Convert a given Binary Tree to Doubly Linked List | Set 2
631
Chapter 96. Convert a given Binary Tree to Doubly Linked List | Set 2
def BTToDLL(root):
# Set the previous pointer
fixPrevPtr(root)
# Set the next pointer and return head of DLL
return fixNextPtr(root)
# Traversses the DLL from left to right
def printList(root):
while(root != None):
print "\t%d" %(root.data),
root = root.right
# Driver program to test above function
root = Node(10)
root.left = Node(12)
root.right = Node(15)
root.left.left = Node(25)
root.left.right = Node(30)
root.right.left = Node(36)
print "\n\t\t Inorder Tree Traversal\n"
inorder(root)
# Static variable pre for function fixPrevPtr
fixPrevPtr.pre = None
head = BTToDLL(root)
print "\n\n\t\tDLL Traversal\n"
printList(head)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
25 12 30 10 36 15
DLL Traversal
25 12 30 10 36 15
Time Complexity: O(n) where n is the number of nodes in given Binary Tree. The solution
simply does two traversals of all Binary Tree nodes.
632
Chapter 96. Convert a given Binary Tree to Doubly Linked List | Set 2
This article is contributed by Bala. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/convert-a-given-binary-tree-to-doubly-linked-list-set-2/
633
Chapter 97
Following two different solutions have been discussed for this problem.
Convert a given Binary Tree to Doubly Linked List | Set 1
Convert a given Binary Tree to Doubly Linked List | Set 2
In this post, a third solution is discussed which seems to be the simplest of all. The idea is
to do inorder traversal of the binary tree. While doing inorder traversal, keep track of the
previously visited node in a variable say prev. For every visited node, make it next of prev
and previous of this node as prev.
634
Chapter 97. Convert a given Binary Tree to Doubly Linked List | Set 3
Thanks to rahul, wishall and all other readers for their useful comments on the above two
posts.
Following is C++ implementation of this solution.
C++
635
Chapter 97. Convert a given Binary Tree to Doubly Linked List | Set 3
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(int data)
{
node* new_node = new node;
new_node->data = data;
new_node->left = new_node->right = NULL;
return (new_node);
}
/* Function to print nodes in a given doubly linked list */
void printList(node *node)
{
while (node!=NULL)
{
cout << node->data << " ";
node = node->right;
}
}
/* Driver program to test above functions*/
int main()
{
// Let us create the tree shown in above diagram
node *root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
// Convert to DLL
node *head = NULL;
BinaryTree2DoubleLinkedList(root, &head);
// Print the converted list
printList(head);
return 0;
}
Java
636
Chapter 97. Convert a given Binary Tree to Doubly Linked List | Set 3
class Node
{
int data;
Node left, right;
public Node(int data)
{
this.data = data;
left = right = null;
}
}
class BinaryTree
{
Node root;
// head --> Pointer to head node of created doubly linked list
Node head;
// Initialize previously visited node as NULL. This is
// static so that the same value is accessible in all recursive
// calls
static Node prev = null;
// A simple recursive function to convert a given Binary tree
// to Doubly Linked List
// root --> Root of Binary Tree
void BinaryTree2DoubleLinkedList(Node root)
{
// Base case
if (root == null)
return;
// Recursively convert left subtree
BinaryTree2DoubleLinkedList(root.left);
// Now convert this node
if (prev == null)
head = root;
else
{
root.left = prev;
prev.right = root;
}
prev = root;
// Finally convert right subtree
BinaryTree2DoubleLinkedList(root.right);
637
Chapter 97. Convert a given Binary Tree to Doubly Linked List | Set 3
}
/* Function to print nodes in a given doubly linked list */
void printList(Node node)
{
while (node != null)
{
System.out.print(node.data + " ");
node = node.right;
}
}
// Driver program to test above functions
public static void main(String[] args)
{
// Let us create the tree as shown in above diagram
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(12);
tree.root.right = new Node(15);
tree.root.left.left = new Node(25);
tree.root.left.right = new Node(30);
tree.root.right.left = new Node(36);
// convert to DLL
tree.BinaryTree2DoubleLinkedList(tree.root);
// Print the converted List
tree.printList(tree.head);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output:
25 12 30 10 36 15
Note that use of static variables like above is not a recommended practice (we have used
static for simplicity). Imagine a situation where same function is called for two or more
trees, the old value of prev would be used in next call for a different tree. To avoid such
problems, we can use double pointer or reference to a pointer.
Time Complexity: The above program does a simple inorder traversal, so time complexity
is O(n) where n is the number of nodes in given binary tree.
638
Chapter 97. Convert a given Binary Tree to Doubly Linked List | Set 3
Source
https://www.geeksforgeeks.org/convert-given-binary-tree-doubly-linked-list-set-3/
639
Chapter 98
Below three different solutions have been discussed for this problem.
Convert a given Binary Tree to Doubly Linked List | Set 1
Convert a given Binary Tree to Doubly Linked List | Set 2
Convert a given Binary Tree to Doubly Linked List | Set 3
In the following implementation, we traverse the tree in inorder fashion. We add nodes at
the beginning of current linked list and update head of the list using pointer to head pointer.
Since we insert at the beginning, we need to process leaves in reverse order. For reverse
640
Chapter 98. Convert a given Binary Tree to Doubly Linked List | Set 4
order, we first traverse the right subtree before the left subtree. i.e. do a reverse inorder
traversal.
C++
641
Chapter 98. Convert a given Binary Tree to Doubly Linked List | Set 4
Java
642
Chapter 98. Convert a given Binary Tree to Doubly Linked List | Set 4
643
Chapter 98. Convert a given Binary Tree to Doubly Linked List | Set 4
}
// Utility function for printing double linked list.
void printList(Node head)
{
System.out.println("Extracted Double Linked List is : ");
while (head != null)
{
System.out.print(head.data + " ");
head = head.right;
}
}
// Driver program to test the above functions
public static void main(String[] args)
{
/* Constructing below tree
5
/ \
3 6
/ \ \
1 4 8
/ \ / \
0 2 7 9 */
BinaryTree tree = new BinaryTree();
tree.root = new Node(5);
tree.root.left = new Node(3);
tree.root.right = new Node(6);
tree.root.left.right = new Node(4);
tree.root.left.left = new Node(1);
tree.root.right.right = new Node(8);
tree.root.left.left.right = new Node(2);
tree.root.left.left.left = new Node(0);
tree.root.right.right.left = new Node(7);
tree.root.right.right.right = new Node(9);
tree.BToDLL(tree.root);
tree.printList(tree.head);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output :
644
Chapter 98. Convert a given Binary Tree to Doubly Linked List | Set 4
0 1 2 3 4 5 6 7 8 9
Time Complexity: O(n), as the solution does a single traversal of given Binary Tree.
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/convert-a-given-binary-tree-to-doubly-linked-list-set-4/
645
Chapter 99
Convert a given Binary tree to a tree that holds Logical AND property - GeeksforGeeks
Given a Binary Tree (Every node has at most 2 children) where each node has value either
0 or 1. Convert a given Binary tree to a tree that holds Logical AND property, i.e., each
node value should be the logical AND between its children.
Examples:
Input : The below tree doesn’t hold the logical AND property
convert it to a tree that holds the property.
1
/ \
1 0
/ \ / \
0 1 1 1
Output :
0
/ \
0 1
/ \ / \
0 1 1 1
The idea is to traverse given binary tree in postorder fashion. For each node check (recur-
sively) if the node has one children then we don’t have any need to check else if the node
has both its child then simply update the node data with the logical AND of its child data.
646
Chapter 99. Convert a given Binary tree to a tree that holds Logical AND property
647
Chapter 99. Convert a given Binary tree to a tree that holds Logical AND property
/* then print the data of node */
printf("%d ", root->data);
/* now recur on right child */
printInorder(root->right);
}
// main function
int main()
{
/* Create following Binary Tree
1
/ \
1 0
/ \ / \
0 1 1 1
*/
Node *root=newNode(0);
root->left=newNode(1);
root->right=newNode(0);
root->left->left=newNode(0);
root->left->right=newNode(1);
root->right->left=newNode(1);
root->right->right=newNode(1);
printf("\n Inorder traversal before conversion ");
printInorder(root);
convertTree(root);
printf("\n Inorder traversal after conversion ");
printInorder(root);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/convert-given-binary-tree-tree-holds-logical-property/
648
Chapter 100
10
/ \
-2 6
/ \ / \
8 -4 7 5
should be changed to
20(4-2+12+6)
/ \
4(8-4) 12(7+5)
/ \ / \
0 0 0 0
Solution:
Do a traversal of the given tree. In the traversal, store the old value of the current node,
recursively call for left and right subtrees and change the value of current node as sum of
the values returned by the recursive calls. Finally return the sum of new value and value
(which is sum of values in the subtree rooted with this node).
C
649
Chapter 100. Convert a given tree to its Sum Tree
#include<stdio.h>
/* A tree node structure */
struct node
{
int data;
struct node *left;
struct node *right;
};
// Convert a given tree to a tree where every node contains sum of values of
// nodes in left and right subtrees in the original tree
int toSumTree(struct node *node)
{
// Base case
if(node == NULL)
return 0;
// Store the old value
int old_val = node->data;
// Recursively call for left and right subtrees and store the sum as
// new value of this node
node->data = toSumTree(node->left) + toSumTree(node->right);
// Return the sum of values of nodes in left and right subtrees and
// old_value of this node
return node->data + old_val;
}
// A utility function to print inorder traversal of a Binary Tree
void printInorder(struct node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
/* Utility function to create a new Binary Tree node */
struct node* newNode(int data)
{
struct node *temp = new struct node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
650
Chapter 100. Convert a given tree to its Sum Tree
return temp;
}
/* Driver function to test above functions */
int main()
{
struct node *root = NULL;
int x;
/* Constructing tree given in the above figure */
root = newNode(10);
root->left = newNode(-2);
root->right = newNode(6);
root->left->left = newNode(8);
root->left->right = newNode(-4);
root->right->left = newNode(7);
root->right->right = newNode(5);
toSumTree(root);
// Print inorder traversal of the converted tree to test result of toSumTree()
printf("Inorder Traversal of the resultant tree is: \n");
printInorder(root);
getchar();
return 0;
}
Java
651
Chapter 100. Convert a given tree to its Sum Tree
// Convert a given tree to a tree where every node contains sum of
// values of nodes in left and right subtrees in the original tree
int toSumTree(Node node)
{
// Base case
if (node == null)
return 0;
// Store the old value
int old_val = node.data;
// Recursively call for left and right subtrees and store the sum
// as new value of this node
node.data = toSumTree(node.left) + toSumTree(node.right);
// Return the sum of values of nodes in left and right subtrees
// and old_value of this node
return node.data + old_val;
}
// A utility function to print inorder traversal of a Binary Tree
void printInorder(Node node)
{
if (node == null)
return;
printInorder(node.left);
System.out.print(node.data + " ");
printInorder(node.right);
}
/* Driver function to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
/* Constructing tree given in the above figure */
tree.root = new Node(10);
tree.root.left = new Node(-2);
tree.root.right = new Node(6);
tree.root.left.left = new Node(8);
tree.root.left.right = new Node(-4);
tree.root.right.left = new Node(7);
tree.root.right.right = new Node(5);
tree.toSumTree(tree.root);
// Print inorder traversal of the converted tree to test result
652
Chapter 100. Convert a given tree to its Sum Tree
// of toSumTree()
System.out.println("Inorder Traversal of the resultant tree is:");
tree.printInorder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal
Output:
Time Complexity: The solution involves a simple traversal of the given tree. So the time
complexity is O(n) where n is the number of nodes in the given Binary Tree.
Source
https://www.geeksforgeeks.org/convert-a-given-tree-to-sum-tree/
653
Chapter 101
Input:
30
/
20
/
10
Output:
20
/ \
10 30
Input:
4
/
3
/
2
/
1
Output:
3 3 2
654
Chapter 101. Convert a normal BST to Balanced BST
/ \ / \ / \
1 4 OR 2 4 OR 1 3 OR ..
\ / \
2 1 4
Input:
4
/ \
3 5
/ \
2 6
/ \
1 7
Output:
4
/ \
2 6
/ \ / \
1 3 5 7
A Simple Solution is to traverse nodes in Inorder and one by one insert into a self-balancing
BST like AVL tree. Time complexity of this solution is O(n Log n) and this solution doesn’t
guarantee
An Efficient Solution can construct balanced BST in O(n) time with minimum possible
height. Below are steps.
1. Traverse given BST in inorder and store result in an array. This step takes O(n) time.
Note that this array would be sorted as inorder traversal of BST always produces
sorted sequence.
2. Build a balanced BST from the above created sorted array using the recursive approach
discussed here. This step also takes O(n) time as we traverse every element exactly
once and processing an element takes O(1) time.
C++
655
Chapter 101. Convert a normal BST to Balanced BST
};
/* This function traverse the skewed binary tree and
stores its nodes pointers in vector nodes[] */
void storeBSTNodes(Node* root, vector<Node*> &nodes)
{
// Base case
if (root==NULL)
return;
// Store nodes in Inorder (which is sorted
// order for BST)
storeBSTNodes(root->left, nodes);
nodes.push_back(root);
storeBSTNodes(root->right, nodes);
}
/* Recursive function to construct binary tree */
Node* buildTreeUtil(vector<Node*> &nodes, int start,
int end)
{
// base case
if (start > end)
return NULL;
/* Get the middle element and make it root */
int mid = (start + end)/2;
Node *root = nodes[mid];
/* Using index in Inorder traversal, construct
left and right subtress */
root->left = buildTreeUtil(nodes, start, mid-1);
root->right = buildTreeUtil(nodes, mid+1, end);
return root;
}
// This functions converts an unbalanced BST to
// a balanced BST
Node* buildTree(Node* root)
{
// Store nodes of given BST in sorted order
vector<Node *> nodes;
storeBSTNodes(root, nodes);
// Constucts BST from nodes[]
int n = nodes.size();
return buildTreeUtil(nodes, 0, n-1);
656
Chapter 101. Convert a normal BST to Balanced BST
}
// Utility function to create a new node
Node* newNode(int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
/* Function to do preorder traversal of tree */
void preOrder(Node* node)
{
if (node == NULL)
return;
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
// Driver program
int main()
{
/* Constructed skewed binary tree is
10
/
8
/
7
/
6
/
5 */
Node* root = newNode(10);
root->left = newNode(8);
root->left->left = newNode(7);
root->left->left->left = newNode(6);
root->left->left->left->left = newNode(5);
root = buildTree(root);
printf("Preorder traversal of balanced "
"BST is : \n");
preOrder(root);
return 0;
657
Chapter 101. Convert a normal BST to Balanced BST
Java
658
Chapter 101. Convert a normal BST to Balanced BST
/* Get the middle element and make it root */
int mid = (start + end) / 2;
Node node = nodes.get(mid);
/* Using index in Inorder traversal, construct
left and right subtress */
node.left = buildTreeUtil(nodes, start, mid - 1);
node.right = buildTreeUtil(nodes, mid + 1, end);
return node;
}
// This functions converts an unbalanced BST to
// a balanced BST
Node buildTree(Node root)
{
// Store nodes of given BST in sorted order
Vector<Node> nodes = new Vector<Node>();
storeBSTNodes(root, nodes);
// Constucts BST from nodes[]
int n = nodes.size();
return buildTreeUtil(nodes, 0, n - 1);
}
/* Function to do preorder traversal of tree */
void preOrder(Node node)
{
if (node == null)
return;
System.out.print(node.data + " ");
preOrder(node.left);
preOrder(node.right);
}
// Driver program to test the above functions
public static void main(String[] args)
{
/* Constructed skewed binary tree is
10
/
8
/
7
/
6
/
659
Chapter 101. Convert a normal BST to Balanced BST
5 */
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(8);
tree.root.left.left = new Node(7);
tree.root.left.left.left = new Node(6);
tree.root.left.left.left.left = new Node(5);
tree.root = tree.buildTree(tree.root);
System.out.println("Preorder traversal of balanced BST is :");
tree.preOrder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output :
Source
https://www.geeksforgeeks.org/convert-normal-bst-balanced-bst/
660
Chapter 102
Input : n = 10
Edge 1: 1 3
Edge 2: 1 6
Edge 3: 1 2
Edge 4: 3 4
Edge 5: 6 8
Edge 6: 2 7
Edge 7: 2 5
Edge 8: 4 9
Edge 9: 4 10
Output : 2
By removing 2 edges we can obtain the forest with even node tree.
Dotted line shows removed edges. Any further removal of edge will not satisfy
the even nodes condition.
Find a subtree with even number of nodes and remove it from rest of tree by removing the
edge connecting it. After removal, we are left with tree with even node only because initially
we have even number of nodes in the tree and removed subtree has also even node. Repeat
661
Chapter 102. Convert a tree to forest of even nodes
the same procedure until we left with the tree that cannot be further decomposed in this
manner.
To do this, the idea is to use Depth First Search to traverse the tree. Implement DFS
function in such a manner that it will return number of nodes in the subtree whose root is
node on which DFS is performed. If the number of nodes is even then remove the edge, else
ignore.
Below is C++ implementation of this approach:
662
Chapter 102. Convert a tree to forest of even nodes
663
Chapter 102. Convert a tree to forest of even nodes
Output:
Source
https://www.geeksforgeeks.org/convert-tree-forest-even-nodes/
664
Chapter 103
Convert an arbitrary Binary Tree to a tree that holds Children Sum Property - Geeks-
forGeeks
Question: Given an arbitrary binary tree, convert it to a binary tree that holds Children
Sum Property. You can only increment data values in any node (You cannot change the
structure of the tree and cannot decrement the value of any node).
For example, the below tree doesn’t hold the children sum property, convert it to a tree that
holds the property.
50
/ \
/ \
7 2
/ \ /\
/ \ / \
3 5 1 30
Algorithm:
Traverse the given tree in post order to convert it, i.e., first change left and right children
to hold the children sum property then change the parent node.
Let difference between node’s data and children sum be diff.
665
Chapter 103. Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
50
/ \
/ \
8 2
/ \ /\
/ \ / \
3 5 1 30
50
/ \
/ \
8 31
/ \ / \
/ \ / \
3 5 1 30
Now convert the root, we have to increment left subtree for converting the root.
50
/ \
/ \
19 31
/ \ / \
/ \ / \
14 5 1 30
Please note the last step – we have incremented 8 to 19, and to fix the subtree we have
incremented 3 to 14.
Implementation:
C
666
Chapter 103. Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
667
Chapter 103. Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
668
Chapter 103. Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
printInorder(node->right);
}
/* Helper function that allocates a new node
with the given data and NULL left and right
pointers. */
struct node* newNode(int data)
{
struct node* node =
(struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions */
int main()
{
struct node *root = newNode(50);
root->left = newNode(7);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->left = newNode(1);
root->right->right = newNode(30);
printf("\n Inorder traversal before conversion ");
printInorder(root);
convertTree(root);
printf("\n Inorder traversal after conversion ");
printInorder(root);
getchar();
return 0;
}
Java
// Java program to convert an arbitrary binary tree to a tree that holds
// children sum property
// A binary tree node
class Node
{
int data;
669
Chapter 103. Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
670
Chapter 103. Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
671
Chapter 103. Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
Output :
Inorder traversal before conversion is :
3 7 5 50 1 2 30
Inorder traversal after conversion is :
14 19 5 50 1 31 30
Time Complexity: O(n^2), Worst case complexity is for a skewed tree such that nodes
are in decreasing order from root to leaf.
Source
https://www.geeksforgeeks.org/convert-an-arbitrary-binary-tree-to-a-tree-that-holds-children-sum-property/
672
Chapter 104
Convert left-right
representation of a binary tree
to down-right
1
/ \
2 3
/ \
4 5
/ / \
6 7 8
Convert the structure of the tree to down-right representation like the below tree.
1
|
2 – 3
|
4 — 5
673
Chapter 104. Convert left-right representation of a binary tree to down-right
| |
6 7 – 8
The conversion should happen in-place, i.e., left child pointer should be used as down pointer
and right child pointer should be used as right sibling pointer.
We strongly recommend to minimize your browser and try this yourself.
The idea is to first convert left and right children, then convert the root. Following is C++
implementation of the idea.
674
Chapter 104. Convert left-right representation of a binary tree to down-right
675
Chapter 104. Convert left-right representation of a binary tree to down-right
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/convert-left-right-representation-bianry-tree-right/
676
Chapter 105
Input:
10
/ \
5 50
/ \ /
1 40 100
Range: [5, 45]
Output: 3
There are three nodes in range, 5, 10 and 40
The idea is to traverse the given binary search tree starting from root. For every node being
visited, check if this node lies in range, if yes, then add 1 to result and recur for both of its
children. If current node is smaller than low value of range, then recur for right child, else
recur for left child.
Below is the implementation of above idea.
C++
677
Chapter 105. Count BST nodes that lie in a given range
678
Chapter 105. Count BST nodes that lie in a given range
root->left = newNode(5);
root->right = newNode(50);
root->left->left = newNode(1);
root->right->left = newNode(40);
root->right->right = newNode(100);
/* Let us constructed BST shown in above example
10
/ \
5 50
/ / \
1 40 100 */
int l = 5;
int h = 45;
cout << "Count of nodes between [" << l << ", " << h
<< "] is " << getCount(root, l, h);
return 0;
}
Java
679
Chapter 105. Count BST nodes that lie in a given range
Output:
680
Chapter 105. Count BST nodes that lie in a given range
Time complexity of the above program is O(h + k) where h is height of BST and k is number
of nodes in given range.
This article is contributed by Gaurav Ahirwar. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/count-bst-nodes-that-are-in-a-given-range/
681
Chapter 106
Input : h = 3
Output : 15
Input : h = 4
Output : 315
682
Chapter 106. Count Balanced Binary Trees of Height h
1. (h-1), (h-2)
2. (h-2), (h-1)
3. (h-1), (h-1)
Hence we can see that the problem has optimal substructure property.
A recursive function to count no of balanced binary trees of height h is:
int countBT(int h)
{
// One tree is possible with height 0 or 1
if (h == 0 || h == 1)
return 1;
return countBT(h-1) * (2 *countBT(h-2) +
countBT(h-1));
}
The time complexity of this recursive approach will be exponential. The recursion tree for
the problem with h = 3 looks like :
As we can see, sub-problems are solved repeatedly. Therefore we store the results as we
compute them.
An efficient dynamic programming approach will be as follows :
CPP
683
Chapter 106. Count Balanced Binary Trees of Height h
PHP
<?php
// PHP program to count
// number of balanced
$mod =1000000007;
function countBT($h)
{
global $mod;
// base cases
$dp[0] = $dp[1] = 1;
for($i = 2; $i <= $h; $i++)
{
$dp[$i] = ($dp[$i - 1] *
((2 * $dp [$i - 2]) %
$mod + $dp[$i - 1]) %
$mod) % $mod;
}
return $dp[$h];
}
// Driver Code
$h = 3;
684
Chapter 106. Count Balanced Binary Trees of Height h
Output :
Source
https://www.geeksforgeeks.org/count-balanced-binary-trees-height-h/
685
Chapter 107
Input :
Output :2
Explanation
In the above tree only two nodes 1 and 2 are non-leaf nodes
We recursively traverse the given tree. While traversing, we count non-leaf nodes in left and
right subtrees and add 1 to the result.
686
Chapter 107. Count Non-Leaf nodes in a Binary Tree
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
/* Computes the number of non-leaf nodes in a tree. */
int countNonleaf(struct Node* root)
{
// Base cases.
if (root == NULL || (root->left == NULL &&
root->right == NULL))
return 0;
// If root is Not NULL and its one of its
// child is also not NULL
return 1 + countNonleaf(root->left) +
countNonleaf(root->right);
}
/* Driver program to test size function*/
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << countNonleaf(root);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/count-non-leaf-nodes-binary-tree/
687
Chapter 108
Input : a = {3, 4, 2, 2, 4, 6}
Q = 2
L = 1 R = 4
L = 2 R = 6
Output : 0
2
Input: a = {1, 2, 3, 5}
Q = 2
L = 1 R = 4
L = 2 R = 4
Output: 1
0
Naive approach : Iterate from range L-R for every query and check if the given element
688
Chapter 108. Count elements which divide all numbers in range L-R
at index-i divide all the numbers in the range. We keep a count for of all the elements which
divides all the numbers. The complexity of every query at worst case will be O(n2 ).
Below is the implementation of Naive Approach :
689
Chapter 108. Count elements which divide all numbers in range L-R
{
int a[] = { 1, 2, 3, 5 };
int n = sizeof(a) / sizeof(a[0]);
int l = 1, r = 4;
cout << answerQuery(a, n, l, r) << endl;
l = 2, r = 4;
cout << answerQuery(a, n, l, r) << endl;
return 0;
}
Output:
1
0
Efficient approach : Use Segment Trees to solve this problem. If an element divides all
the numbers in a given range, then the element is the minimum number in that range and it
is the gcd of all elements in the given range L-R. So the count of the number of minimums in
range L-R, given that minimum is equal to the gcd of that range will be our answer to every
query. The problem boils down to finding the GCD, MINIMUMand countMINIMUM
for every range using Segment trees. On every node of the tree, three values are stored.
On querying for a given range, if the gcd and minimum of the given range are equal, count-
MINIMUM is returned as the answer. If they are unequal, 0 is returned as the answer.
Below is the implementation of efficient approach :
690
Chapter 108. Count elements which divide all numbers in range L-R
// function to construct the tree
void buildtree(int low, int high,
int pos, int a[])
{
// base condition
if (low == high)
{
// initially always gcd and min
// are same at leaf node
tree[pos].min = tree[pos].gcd = a[low];
tree[pos].cnt = 1;
return;
}
int mid = (low + high) >> 1;
// left-subtree
buildtree(low, mid, 2 * pos + 1, a);
// right-subtree
buildtree(mid + 1, high, 2 * pos + 2, a);
// finds gcd of left and rigth subtree
tree[pos].gcd = __gcd(tree[2 * pos + 1].gcd,
tree[2 * pos + 2].gcd);
// left subtree has the minimum element
if (tree[2 * pos + 1].min < tree[2 * pos + 2].min)
{
tree[pos].min = tree[2 * pos + 1].min;
tree[pos].cnt = tree[2 * pos + 1].cnt;
}
// right subtree has the minimum element
else
if (tree[2 * pos + 1].min > tree[2 * pos + 2].min)
{
tree[pos].min = tree[2 * pos + 2].min;
tree[pos].cnt = tree[2 * pos + 2].cnt;
}
// both subtree has the same minimum element
else
{
tree[pos].min = tree[2 * pos + 1].min;
tree[pos].cnt = tree[2 * pos + 1].cnt +
691
Chapter 108. Count elements which divide all numbers in range L-R
692
Chapter 108. Count elements which divide all numbers in range L-R
693
Chapter 108. Count elements which divide all numbers in range L-R
int l = 1, r = 4;
// answers 1-st query
cout << answerQuery(a, n, l, r) << endl;
l = 2, r = 6;
// answers 2nd query
cout << answerQuery(a, n, l, r) << endl;
return 0;
}
Output:
0
2
Time Complexity: Time Complexity for tree construction is O(n logn) since tree con-
struction takes O(n) and finding out gcd takes O(log n). The time taken for every query in
worst case will be O(log n * log n) since the inbuilt function __gcd takes O(log
n)
Source
https://www.geeksforgeeks.org/count-elements-which-divide-all-numbers-in-range-l-r/
694
Chapter 109
695
Chapter 109. Count full nodes in a Binary tree (Iterative and Recursive)
Nodes 2 and 6 are full nodes has both child’s. So count of full nodes in the above tree is 2
Method: Iterative
The idea is to use level-order traversal to solve this problem efficiently.
696
Chapter 109. Count full nodes in a Binary tree (Iterative and Recursive)
count++;
if (temp->left != NULL)
q.push(temp->left);
if (temp->right != NULL)
q.push(temp->right);
}
return count;
}
/* Helper function that allocates a new Node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Driver program
int main(void)
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
struct Node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
cout << getfullCount(root);
return 0;
}
Java
697
Chapter 109. Count full nodes in a Binary tree (Iterative and Recursive)
698
Chapter 109. Count full nodes in a Binary tree (Iterative and Recursive)
Python
# Python program to count
# full nodes in a Binary Tree
# using iterative approach
699
Chapter 109. Count full nodes in a Binary tree (Iterative and Recursive)
# A node structure
class Node:
# A utility function to create a new node
def __init__(self ,key):
self.data = key
self.left = None
self.right = None
# Iterative Method to count full nodes of binary tree
def getfullCount(root):
# Base Case
if root is None:
return 0
# Create an empty queue for level order traversal
queue = []
# Enqueue Root and initialize count
queue.append(root)
count = 0 #initialize count for full nodes
while(len(queue) > 0):
node = queue.pop(0)
# if it is full node then increment count
if node.left is not None and node.right is not None:
count = count+1
# Enqueue left child
if node.left is not None:
queue.append(node.left)
# Enqueue right child
if node.right is not None:
queue.append(node.right)
return count
# Driver Program to test above function
root = Node(2)
root.left = Node(7)
root.right = Node(5)
root.left.right = Node(6)
root.left.right.left = Node(1)
root.left.right.right = Node(11)
root.right.right = Node(9)
root.right.right.left = Node(4)
700
Chapter 109. Count full nodes in a Binary tree (Iterative and Recursive)
print "%d" %(getfullCount(root))
Output:
701
Chapter 109. Count full nodes in a Binary tree (Iterative and Recursive)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Driver program
int main(void)
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
*/
struct Node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
cout << getfullCount(root);
return 0;
}
Output:
702
Chapter 109. Count full nodes in a Binary tree (Iterative and Recursive)
Source
https://www.geeksforgeeks.org/count-full-nodes-binary-tree-iterative-recursive/
703
Chapter 110
Output : 3
Nodes 7, 5 and 9 are half nodes as one of
their child is Null. So count of half nodes
in the above tree is 3
Iterative
The idea is to use level-order traversal to solve this problem efficiently.
704
Chapter 110. Count half nodes in a Binary tree (Iterative and Recursive)
705
Chapter 110. Count half nodes in a Binary tree (Iterative and Recursive)
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Driver program
int main(void)
{
/* 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree shown in
above example */
struct Node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
cout << gethalfCount(root);
return 0;
}
Java
706
Chapter 110. Count half nodes in a Binary tree (Iterative and Recursive)
left = null;
right = null;
}
}
// Class to count half nodes of Tree
class BinaryTree
{
Node root;
/* Function to get the count of half Nodes in
a binary tree*/
int gethalfCount()
{
// If tree is empty
if (root==null)
return 0;
// Do level order traversal starting from root
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
int count=0; // Initialize count of half nodes
while (!queue.isEmpty())
{
Node temp = queue.poll();
if (temp.left!=null && temp.right==null ||
temp.left==null && temp.right!=null)
count++;
// Enqueue left child
if (temp.left != null)
queue.add(temp.left);
// Enqueue right child
if (temp.right != null)
queue.add(temp.right);
}
return count;
}
public static void main(String args[])
{
/* 2
/ \
7 5
707
Chapter 110. Count half nodes in a Binary tree (Iterative and Recursive)
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree shown in
above example */
BinaryTree tree_level = new BinaryTree();
tree_level.root = new Node(2);
tree_level.root.left = new Node(7);
tree_level.root.right = new Node(5);
tree_level.root.left.right = new Node(6);
tree_level.root.left.right.left = new Node(1);
tree_level.root.left.right.right = new Node(11);
tree_level.root.right.right = new Node(9);
tree_level.root.right.right.left = new Node(4);
System.out.println(tree_level.gethalfCount());
}
}
Python
# Python program to count
# half nodes in a Binary Tree
# using iterative approach
# A node structure
class Node:
# A utility function to create a new node
def __init__(self ,key):
self.data = key
self.left = None
self.right = None
# Iterative Method to count half nodes of binary tree
def gethalfCount(root):
# Base Case
if root is None:
return 0
# Create an empty queue for level order traversal
queue = []
# Enqueue Root and initialize count
708
Chapter 110. Count half nodes in a Binary tree (Iterative and Recursive)
queue.append(root)
count = 0 #initialize count for half nodes
while(len(queue) > 0):
node = queue.pop(0)
# if it is half node then increment count
if node.left is not None and node.right is None or node.left is None and node.right is no
count = count+1
#Enqueue left child
if node.left is not None:
queue.append(node.left)
# Enqueue right child
if node.right is not None:
queue.append(node.right)
return count
#Driver Program to test above function
root = Node(2)
root.left = Node(7)
root.right = Node(5)
root.left.right = Node(6)
root.left.right.left = Node(1)
root.left.right.right = Node(11)
root.right.right = Node(9)
root.right.right.left = Node(4)
print "%d" %(gethalfCount(root))
Output:
709
Chapter 110. Count half nodes in a Binary tree (Iterative and Recursive)
710
Chapter 110. Count half nodes in a Binary tree (Iterative and Recursive)
1 11 4
Let us create Binary Tree shown in
above example */
struct Node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left = newNode(1);
root->left->right->right = newNode(11);
root->right->right = newNode(9);
root->right->right->left = newNode(4);
cout << gethalfCount(root);
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/count-half-nodes-in-a-binary-tree-iterative-and-recursive/
711
Chapter 111
Count pairs in a binary tree whose sum is equal to a given value x - GeeksforGeeks
Given a binary tree containing n distinct numbers and a value x. The problem is to count
pairs in the given binary tree whose sum is equal to the given value x.
Examples:
Input :
5
/ \
3 7
/ \ / \
2 4 6 8
x = 10
Output : 3
The pairs are (3, 7), (2, 8) and (4, 6).
Naive Approach: One by one get each node of the binary tree through any of the tree
traversals method. Pass the node say temp, the root of the tree and value x to another
function say findPair(). In the function with the help of the root pointer traverse the tree
again. One by one sum up these nodes with temp and check whether sum == x. If so,
increment count. Calculate count = count / 2 as a single pair has been counted twice by
the aforementioned method.
712
Chapter 111. Count pairs in a binary tree whose sum is equal to a given value x
713
Chapter 111. Count pairs in a binary tree whose sum is equal to a given value x
// check whether pair exists for current node 'curr'
// in the binary tree that sum up to 'x'
if (findPair(root, curr, x))
count++;
// recursively count pairs in left subtree
countPairs(root, curr->left, x, count);
// recursively count pairs in right subtree
countPairs(root, curr->right, x, count);
}
// Driver program to test above
int main()
{
// formation of binary tree
Node* root = getNode(5); /* 5 */
root->left = getNode(3); /* / \ */
root->right = getNode(7); /* 3 7 */
root->left->left = getNode(2); /* / \ / \ */
root->left->right = getNode(4); /* 2 4 6 8 */
root->right->left = getNode(6);
root->right->right = getNode(8);
int x = 10;
int count = 0;
countPairs(root, root, x, count);
count = count / 2;
cout << "Count = " << count;
return 0;
}
Output:
Count = 3
1. Convert given binary tree to doubly linked list. Refer this post.
2. Sort the doubly linked list obtained in Step 1. Refer this post.
3. Count Pairs in sorted doubly linked with sum equal to ‘x’. Refer this post.
714
Chapter 111. Count pairs in a binary tree whose sum is equal to a given value x
715
Chapter 111. Count pairs in a binary tree whose sum is equal to a given value x
// Recursively convert left subtree
BToDLL(root->left, head_ref);
}
// Split a doubly linked list (DLL) into 2 DLLs of
// half sizes
Node* split(Node* head)
{
Node *fast = head, *slow = head;
while (fast->right && fast->right->right) {
fast = fast->right->right;
slow = slow->right;
}
Node* temp = slow->right;
slow->right = NULL;
return temp;
}
// Function to merge two sorted doubly linked lists
Node* merge(Node* first, Node* second)
{
// If first linked list is empty
if (!first)
return second;
// If second linked list is empty
if (!second)
return first;
// Pick the smaller value
if (first->data < second->data) {
first->right = merge(first->right, second);
first->right->left = first;
first->left = NULL;
return first;
}
else {
second->right = merge(first, second->right);
second->right->left = second;
second->left = NULL;
return second;
}
}
// Function to do merge sort
Node* mergeSort(Node* head)
{
716
Chapter 111. Count pairs in a binary tree whose sum is equal to a given value x
717
Chapter 111. Count pairs in a binary tree whose sum is equal to a given value x
}
// function to count pairs in a binary tree
// whose sum is equal to given value x
int countPairs(Node* root, int x)
{
Node* head = NULL;
int count = 0;
// Convert binary tree to
// doubly linked list
BToDLL(root, &head);
// sort DLL
head = mergeSort(head);
// count pairs
return pairSum(head, x);
}
// Driver program to test above
int main()
{
// formation of binary tree
Node* root = getNode(5); /* 5 */
root->left = getNode(3); /* / \ */
root->right = getNode(7); /* 3 7 */
root->left->left = getNode(2); /* / \ / \ */
root->left->right = getNode(4); /* 2 4 6 8 */
root->right->left = getNode(6);
root->right->right = getNode(8);
int x = 10;
cout << "Count = "
<< countPairs(root, x);
return 0;
}
Output:
Count = 3
718
Chapter 111. Count pairs in a binary tree whose sum is equal to a given value x
Source
https://www.geeksforgeeks.org/count-pairs-in-a-binary-tree-whose-sum-is-equal-to-a-given-value-x/
719
Chapter 112
Input :
5
/ \
-10 3
/ \ / \
9 8 -4 7
x = 7
Output : 2
There are 2 subtrees with sum 7.
-10
/ \
9 8
720
Chapter 112. Count subtrees that sum up to a given value x
countSubtreesWithSumX(root, count, x)
if !root then
return 0
ls = countSubtreesWithSumX(root->left, count, x)
rs = countSubtreesWithSumX(root->right, count, x)
sum = ls + rs + root->data
if sum == x then
count++
return sum
countSubtreesWithSumXUtil(root, x)
if !root then
return 0
Initialize count = 0
ls = countSubtreesWithSumX(root->left, count, x)
rs = countSubtreesWithSumX(root->right, count, x)
if (ls + rs + root->data) == x
count++
return count
C++
721
Chapter 112. Count subtrees that sum up to a given value x
// put in the data
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// function to count subtress that
// sum up to a given value x
int countSubtreesWithSumX(Node* root,
int& count, int x)
{
// if tree is empty
if (!root)
return 0;
// sum of nodes in the left subtree
int ls = countSubtreesWithSumX(root->left, count, x);
// sum of nodes in the right subtree
int rs = countSubtreesWithSumX(root->right, count, x);
// sum of nodes in the subtree rooted
// with 'root->data'
int sum = ls + rs + root->data;
// if true
if (sum == x)
count++;
// return subtree's nodes sum
return sum;
}
// utility function to count subtress that
// sum up to a given value x
int countSubtreesWithSumXUtil(Node* root, int x)
{
// if tree is empty
if (!root)
return 0;
int count = 0;
// sum of nodes in the left subtree
int ls = countSubtreesWithSumX(root->left, count, x);
// sum of nodes in the right subtree
722
Chapter 112. Count subtrees that sum up to a given value x
Java
// Java program to find if
// there is a subtree with
// given sum
import java.util.*;
class GFG
{
// structure of a node
// of binary tree
static class Node
{
723
Chapter 112. Count subtrees that sum up to a given value x
int data;
Node left, right;
}
static class INT
{
int v;
INT(int a)
{
v = a;
}
}
// function to get a new node
static Node getNode(int data)
{
// allocate space
Node newNode = new Node();
// put in the data
newNode.data = data;
newNode.left = newNode.right = null;
return newNode;
}
// function to count subtress that
// sum up to a given value x
static int countSubtreesWithSumX(Node root,
INT count, int x)
{
// if tree is empty
if (root == null)
return 0;
// sum of nodes in the left subtree
int ls = countSubtreesWithSumX(root.left,
count, x);
// sum of nodes in the right subtree
int rs = countSubtreesWithSumX(root.right,
count, x);
// sum of nodes in the subtree
// rooted with ‘root.data’
int sum = ls + rs + root.data;
// if true
if (sum == x)
count.v++;
// return subtree’s nodes sum
return sum;
}
724
Chapter 112. Count subtrees that sum up to a given value x
// utility function to
// count subtress that
// sum up to a given value x
static int countSubtreesWithSumXUtil(Node root,
int x)
{
// if tree is empty
if (root == null)
return 0;
INT count = new INT(0);
// sum of nodes in the left subtree
int ls = countSubtreesWithSumX(root.left,
count, x);
// sum of nodes in the right subtree
int rs = countSubtreesWithSumX(root.right,
count, x);
// if tree’s nodes sum == x
if ((ls + rs + root.data) == x)
count.v++;
// required count of subtrees
return count.v;
}
// Driver Code
public static void main(String args[])
{
/* binary tree creation
5
/\
-10 3
/\/\
9 8 -4 7
*/
Node root = getNode(5);
root.left = getNode(-10);
root.right = getNode(3);
root.left.left = getNode(9);
root.left.right = getNode(8);
root.right.left = getNode(-4);
root.right.right = getNode(7);
int x = 7;
System.out.println(“Count = ” +
countSubtreesWithSumXUtil(root, x));
}
}
725
Chapter 112. Count subtrees that sum up to a given value x
Count = 2
Source
https://www.geeksforgeeks.org/count-subtress-sum-given-value-x/
726
Chapter 113
Count the number of nodes at given level in a tree using BFS. - GeeksforGeeks
Given a tree represented as undirected graph. Count the number of nodes at given level l.
It may be assumed that vertex 0 is root of the tree.
Examples:
Input : 7
0 1
0 2
1 3
1 4
1 5
2 6
2
Output : 4
Input : 6
0 1
0 2
1 3
2 4
2 5
2
Output : 3
BFS is a traversing algorithm which start traversing from a selected node (source or starting
node) and traverse the graph layer wise thus exploring the neighbour nodes (nodes which
727
Chapter 113. Count the number of nodes at given level in a tree using BFS.
are directly connected to source node). Then, move towards the next-level neighbour nodes.
As the name BFS suggests, traverse the graph breadth wise as follows:
1. First move horizontally and visit all the nodes of the current layer.
2. Move to the next layer.
In this code, while visiting each node, the level of that node is set with an increment in the
level of its parent node i.e., level[child] = level[parent] + 1. This is how the level of each
node is determined. The root node lies at level zero in the tree.
Explanation :
0 Level 0
/ \
1 2 Level 1
/ |\ |
3 4 5 6 Level 2
Given a tree with 7 nodes and 6 edges in which node 0 lies at 0 level. Level of 1 can be
updated as : level[1] = level[0] +1 as 0 is the parent node of 1. Similarly, the level of other
nodes can be updated by adding 1 to the level of their parent.
level[2] = level[0] + 1, i.e level[2] = 0 + 1 = 1.
level[3] = level[1] + 1, i.e level[3] = 1 + 1 = 2.
level[4] = level[1] + 1, i.e level[4] = 1 + 1 = 2.
level[5] = level[1] + 1, i.e level[5] = 1 + 1 = 2.
level[6] = level[2] + 1, i.e level[6] = 1 + 1 = 2.
Then, count of number of nodes which are at level l(i.e, l=2) is 4 (node:- 3, 4, 5, 6)
C++
728
Chapter 113. Count the number of nodes at given level in a tree using BFS.
729
Chapter 113. Count the number of nodes at given level in a tree using BFS.
visited[s] = true;
queue.push_back(s);
level[s] = 0;
while (!queue.empty()) {
// Dequeue a vertex from
// queue and print it
s = queue.front();
queue.pop_front();
// Get all adjacent vertices
// of the dequeued vertex s.
// If a adjacent has not been
// visited, then mark it
// visited and enqueue it
for (auto i = adj[s].begin();
i != adj[s].end(); ++i) {
if (!visited[*i]) {
// Setting the level
// of each node with
// an increment in the
// level of parent node
level[*i] = level[s] + 1;
visited[*i] = true;
queue.push_back(*i);
}
}
}
int count = 0;
for (int i = 0; i < V; i++)
if (level[i] == l)
count++;
return count;
}
// Driver program to test
// methods of graph class
int main()
{
// Create a graph given
// in the above diagram
Graph g(6);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
730
Chapter 113. Count the number of nodes at given level in a tree using BFS.
g.addEdge(2, 4);
g.addEdge(2, 5);
int level = 2;
cout << g.BFS(0, level);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/count-number-nodes-given-level-using-bfs/
731
Chapter 114
Input : root
/ \ \
t a b
| | |
h n y
| | \ |
e s y e
/ | |
i r w
| | |
r e e
|
r
Output : 8
Explanation : Words formed in the Trie :
"the", "a", "there", "answer", "any", "by",
"bye", "their".
In Trie structure, we have a field to store end of word marker, we call it isLeaf in below
implementation. To count words, we need to simply traverse the Trie and count all nodes
where isLeaf is set.
732
Chapter 114. Counting the number of words in a Trie
C++
733
Chapter 114. Counting the number of words in a Trie
Java
734
Chapter 114. Counting the number of words in a Trie
735
Chapter 114. Counting the number of words in a Trie
// Leaf denotes end of a word
if (root.isLeaf)
result++;
for (int i = 0; i < ALPHABET_SIZE; i++)
if (root.children[i] != null )
result += wordCount(root.children[i]);
return result;
}
// Driver Program
public static void main(String args[])
{
// Input keys (use only 'a' through 'z'
// and lower case)
String keys[] = {"the", "a", "there", "answer",
"any", "by", "bye", "their"};
root = new TrieNode();
// Construct Trie
for (int i = 0; i < keys.length; i++)
insert(keys[i]);
System.out.println(wordCount(root));
}
}
// This code is contributed by Sumit Ghosh
Output:
Source
https://www.geeksforgeeks.org/counting-number-words-trie/
736
Chapter 115
1. Left pointer of ternary tree should act as prev pointer of doubly linked list.
2. Middle pointer of ternary tree should not point to anything.
3. Right pointer of ternary tree should act as next pointer of doubly linked list.
4. Each node of ternary tree is inserted into doubly linked list before its subtrees and for
any node, its left child will be inserted first, followed by mid and right child (if any).
For the above example, the linked list formed for below tree should be NULL 5 1 4 8 11 6
7 15 63 31 55 65 -> NULL
737
Chapter 115. Create a Doubly Linked List from a Ternary Tree
We strongly recommend you to minimize your browser and try this yourself
first.
The idea is to traverse the tree in preoder fashion similar to binary tree preorder traversal.
Here, when we visit a node, we will insert it into doubly linked list in the end using a tail
pointer. That we use to maintain the required insertion order. We then recursively call for
left child, middle child and right child in that order.
Below is the implementation of this idea.
C++
738
Chapter 115. Create a Doubly Linked List from a Ternary Tree
node->data = data;
node->left = node->middle = node->right = NULL;
return node;
}
/* Utility function that constructs doubly linked list
by inserting current node at the end of the doubly
linked list by using a tail pointer */
void push(Node** tail_ref, Node* node)
{
// initilize tail pointer
if (*tail_ref == NULL)
{
*tail_ref = node;
// set left, middle and right child to point
// to NULL
node->left = node->middle = node->right = NULL;
return;
}
// insert node in the end using tail pointer
(*tail_ref)->right = node;
// set prev of node
node->left = (*tail_ref);
// set middle and right child to point to NULL
node->right = node->middle = NULL;
// now tail pointer will point to inserted node
(*tail_ref) = node;
}
/* Create a doubly linked list out of given a ternary tree.
by traversing the tree in preoder fashion. */
Node* TernaryTreeToList(Node* root, Node** head_ref)
{
// Base case
if (root == NULL)
return NULL;
//create a static tail pointer
static Node* tail = NULL;
// store left, middle and right nodes
// for future calls.
739
Chapter 115. Create a Doubly Linked List from a Ternary Tree
740
Chapter 115. Create a Doubly Linked List from a Ternary Tree
root->right->middle = newNode(55);
root->right->right = newNode(65);
Node* head = NULL;
TernaryTreeToList(root, &head);
printList(head);
return 0;
}
Java
741
Chapter 115. Create a Doubly Linked List from a Ternary Tree
//update the tail position.
tail = node;
}
/* Create a doubly linked list out of given a ternary tree.
by traversing the tree in preoder fashion. */
public static void ternaryTree(newNode node,newNode head)
{
if(node == null)
return;
newNode left = node.left;
newNode middle = node.middle;
newNode right = node.right;
if(tail != node)
// already root is in the tail so dont push
// the node when it was root.In the first
// case both node and tail have root in them.
push(node);
// First the left child is to be taken.
// Then middle and then right child.
ternaryTree(left,head);
ternaryTree(middle,head);
ternaryTree(right,head);
}
//function to initiate the list process.
public static newNode startTree(newNode root)
{
//Initiate the head and tail with root.
newNode head = root;
tail = root;
ternaryTree(root,head);
//since the head,root are passed
// with reference the changes in
// root will be reflected in head.
return head;
}
// Utility function for printing double linked list.
public static void printList(newNode head)
{
System.out.print("Created Double Linked list is:\n");
while(head != null)
{
742
Chapter 115. Create a Doubly Linked List from a Ternary Tree
Output:
Improved By : MvssTeja
Source
https://www.geeksforgeeks.org/create-doubly-linked-list-ternary-ree/
743
Chapter 116
1
/ \
2 3
/ \ / \
4 5 6 7
Odd loop
1 -> 5 -> 3 -> 7 -> 1(again pointing to first node
in the loop)
Even loop
744
Chapter 116. Create loops of even and odd values in a binary tree
1. Add pointers of the nodes having even and odd numbers to even_ptrs and odd_ptrs
arrays respectively. Through any tree traversal we could get the respective node
pointers.
2. For both the even_ptrs and odd_ptrs array, perform:
• As the array contains node pointers, consider an element at ith index, let it be
node, and the assign node->abtr = element at (i+1)th index.
• For last element of the array, node->abtr = element at index 0.
745
Chapter 116. Create loops of even and odd values in a binary tree
746
Chapter 116. Create loops of even and odd values in a binary tree
int main()
{
// Binary tree formation
struct Node* root = NULL;
root = newNode(1); /* 1 */
root->left = newNode(2); /* / \ */
root->right = newNode(3); /* 2 3 */
root->left->left = newNode(4); /* / \ / \ */
root->left->right = newNode(5); /* 4 5 6 7 */
root->right->left = newNode(6);
root->right->right = newNode(7);
createLoops(root);
// traversing odd loop from any
// random odd node
cout << "Odd nodes: ";
traverseLoop(root->right);
cout << endl << "Even nodes: ";
// traversing even loop from any
// random even node
traverseLoop(root->left);
return 0;
}
Output:
Odd nodes: 3 7 1 5
Even nodes: 2 4 6
Time Complexity: Equal to the time complexity of any recursive tree traversal which is
O(n)
Source
https://www.geeksforgeeks.org/create-loops-of-even-and-odd-values-in-a-binary-tree/
747
Chapter 117
Examples:
748
Chapter 117. Creating a tree with Left-Child Right-Sibling Representation
749
Chapter 117. Creating a tree with Left-Child Right-Sibling Representation
Java
750
Chapter 117. Creating a tree with Left-Child Right-Sibling Representation
static class NodeTemp
{
int data;
NodeTemp next, child;
public NodeTemp(int data)
{
this.data = data;
next = child = null;
}
}
// Adds a sibling to a list with starting with n
static public NodeTemp addSibling(NodeTemp node, int data)
{
if(node == null)
return null;
while(node.next != null)
node = node.next;
return(node.next = new NodeTemp(data));
}
// Add child Node to a Node
static public NodeTemp addChild(NodeTemp node,int data)
{
if(node == null)
return null;
// Check if child is not empty.
if(node.child != null)
return(addSibling(node.child,data));
else
return(node.child = new NodeTemp(data));
}
// Traverses tree in level order
static public void traverseTree(NodeTemp root)
{
if(root == null)
return;
while(root != null)
{
System.out.print(root.data + " ");
if(root.child != null)
traverseTree(root.child);
root = root.next;
}
}
751
Chapter 117. Creating a tree with Left-Child Right-Sibling Representation
// Driver code
public static void main(String args[])
{
/* Let us create below tree
* 10
* / / \ \
* 2 3 4 5
* | / | \
* 6 7 8 9 */
// Left child right sibling
/* 10
* |
* 2 -> 3 -> 4 -> 5
* | |
* 6 7 -> 8 -> 9 */
NodeTemp root = new NodeTemp(10);
NodeTemp n1 = addChild(root,2);
NodeTemp n2 = addChild(root,3);
NodeTemp n3 = addChild(root,4);
NodeTemp n4 = addChild(n3,6);
NodeTemp n5 = addChild(root,5);
NodeTemp n6 = addChild(n5,7);
NodeTemp n7 = addChild(n5,8);
NodeTemp n8 = addChild(n5,9);
traverseTree(root);
}
}
// This code is contributed by M.V.S.Surya Teja.
Output:
10 2 3 4 6 5 7 8 9
Improved By : MvssTeja
Source
https://www.geeksforgeeks.org/creating-tree-left-child-right-sibling-representation/
752
Chapter 118
a ---> b
b ---> c
b ---> d
a ---> e
Print the tree that would form when each pair of these links that has the same character
as start and end point is joined together. You have to maintain fidelity w.r.t. the height of
nodes, i.e. nodes at height n from root should be printed at same row or column. For set of
links given above, tree printed should be –
-->a
|-->b
| |-->c
| |-->d
|-->e
Note that these links need not form a single tree; they could form, ahem, a forest. Consider
the following links
a ---> b
a ---> g
b ---> c
c ---> d
d ---> e
c ---> f
z ---> y
y ---> x
x ---> w
753
Chapter 118. Custom Tree Problem
-->a
|-->b
| |-->c
| | |-->d
| | | |-->e
| | |-->f
|-->g
-->z
|-->y
| |-->x
| | |-->w
You can assume that given links can form a tree or forest of trees only, and there are no
duplicates among links.
Solution: The idea is to maintain two arrays, one array for tree nodes and other for trees
themselves (we call this array forest). An element of the node array contains the TreeNode
object that corresponds to respective character. An element of the forest array contains
Tree object that corresponds to respective root of tree.
It should be obvious that the crucial part is creating the forest here, once it is created,
printing it out in required format is straightforward. To create the forest, following procedure
is used –
It should be clear that this procedure runs in linear time in number of nodes as well as
of links – it makes only one pass over the links. It also requires linear space in terms of
alphabet size.
Following is Java implementation of above algorithm. In the following implementation
characters are assumed to be only lower case characters from ‘a’ to ‘z’.
754
Chapter 118. Custom Tree Problem
// The main class that represents tree and has main method
public class Tree {
private TreeNode root;
/* Returns an array of trees from links input. Links are assumed to
be Strings of the form "<s> <e>" where <s> and <e> are starting
and ending points for the link. The returned array is of size 26
and has non-null values at indexes corresponding to roots of trees
in output */
public Tree[] buildFromLinks(String [] links) {
// Create two arrays for nodes and forest
TreeNode[] nodes = new TreeNode[26];
Tree[] forest = new Tree[26];
// Process each link
for (String link : links) {
// Find the two ends of current link
String[] ends = link.split(" ");
int start = (int) (ends[0].charAt(0) - 'a'); // Start node
int end = (int) (ends[1].charAt(0) - 'a'); // End node
// If start of link not seen before, add it two both arrays
if (nodes[start] == null)
{
nodes[start] = new TreeNode((char) (start + 'a'));
// Note that it may be removed later when this character is
// last character of a link. For example, let we first see
// a--->b, then c--->a. We first add 'a' to array of trees
// and when we see link c--->a, we remove it from trees array.
forest[start] = new Tree(nodes[start]);
}
// If end of link is not seen before, add it to the nodes array
if (nodes[end] == null)
nodes[end] = new TreeNode((char) (end + 'a'));
// If end of link is seen before, remove it from forest if
// it exists there.
else forest[end] = null;
// Establish Parent-Child Relationship between Start and End
nodes[start].addChild(nodes[end], end);
}
755
Chapter 118. Custom Tree Problem
return forest;
}
// Constructor
public Tree(TreeNode root) { this.root = root; }
public static void printForest(String[] links)
{
Tree t = new Tree(new TreeNode('\0'));
for (Tree t1 : t.buildFromLinks(links)) {
if (t1 != null)
{
t1.root.printTreeIdented("");
System.out.println("");
}
}
}
// Driver method to test
public static void main(String[] args) {
String [] links1 = {"a b", "b c", "b d", "a e"};
System.out.println("------------ Forest 1 ----------------");
printForest(links1);
String [] links2 = {"a b", "a g", "b c", "c d", "d e", "c f",
"z y", "y x", "x w"};
System.out.println("------------ Forest 2 ----------------");
printForest(links2);
}
}
// Class to represent a tree node
class TreeNode {
TreeNode []children;
char c;
// Adds a child 'n' to this node
public void addChild(TreeNode n, int index) { this.children[index] = n;}
// Constructor
public TreeNode(char c) { this.c = c; this.children = new TreeNode[26];}
// Recursive method to print indented tree rooted with this node.
public void printTreeIdented(String indent) {
System.out.println(indent + "-->" + c);
for (TreeNode child : children) {
if (child != null)
child.printTreeIdented(indent + " |");
756
Chapter 118. Custom Tree Problem
}
}
}
Output:
-->z
|-->y
| |-->x
| | |-->w
Exercise:
In the above implementation, endpoints of input links are assumed to be from set of only
26 characters. Extend the implementation where endpoints are strings of any length.
This article is contributed by Ciphe. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/custom-tree-problem/
757
Chapter 119
DFS for a n-ary tree (acyclic graph) represented as adjacency list - GeeksforGeeks
A tree consisting of n nodes is given, we need to print its DFS.
Examples :
C++
758
Chapter 119. DFS for a n-ary tree (acyclic graph) represented as adjacency list
Java
759
Chapter 119. DFS for a n-ary tree (acyclic graph) represented as adjacency list
// DFS on tree
public static void dfs(LinkedList<Integer> list[],
int node, int arrival)
{
// Printing traversed node
System.out.println(node);
// Traversing adjacent edges
for (int i = 0; i < list[node].size(); i++) {
// Not traversing the parent node
if (list[node].get(i) != arrival)
dfs(list, list[node].get(i), node);
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
// Number of nodes
int nodes = 5;
// Adjacency list
LinkedList<Integer> list[] = new LinkedList[nodes+1];
for (int i = 0; i < list.length; i ++){
list[i] = new LinkedList<Integer>();
}
// Designing the tree
list[1].add(2);
list[2].add(1);
list[1].add(3);
list[3].add(1);
list[2].add(4);
list[4].add(2);
list[3].add(5);
list[5].add(3);
// Function call
dfs(list, 1, 0);
760
Chapter 119. DFS for a n-ary tree (acyclic graph) represented as adjacency list
}
}
// This code is contributed by Arnav Kr. Mandal.
Output:
1
2
4
3
5
Source
https://www.geeksforgeeks.org/dfs-n-ary-tree-acyclic-graph-represented-adjacency-list/
761
Chapter 120
Decision Tree
762
Chapter 120. Decision Tree
763
Chapter 120. Decision Tree
process is then repeated for the subtree rooted at the new node.
The decision tree in above figure classifies a particular morning according to whether it is
suitable for playing tennis and returning the classification associated with the particular
leaf.(in this case Yes or No).
For example,the instance
would be sorted down the leftmost branch of this decision tree and would therefore be
classified as a negative instance.
In other words we can say that decision tree represent a disjunction of conjunctions of
constraints on the attribute values of instances.
• Decision trees are less appropriate for estimation tasks where the goal is to predict
the value of a continuous attribute.
• Decision trees are prone to errors in classification problems with many class and rela-
tively small number of training examples.
• Decision tree can be computationally expensive to train. The process of growing a
decision tree is computationally expensive. At each node, each candidate splitting field
must be sorted before its best split can be found. In some algorithms, combinations
of fields are used and a search must be made for optimal combining weights. Pruning
algorithms can also be expensive since many candidate sub-trees must be formed and
compared.
References :
Machine Learning, Tom Mitchell, McGraw Hill, 1997.
In the next post we will be discussing about ID3 algorithm for the construction of Decision
tree given by J. R. Quinlan.
Source
https://www.geeksforgeeks.org/decision-tree/
764
Chapter 121
1
/ \
2 3
/ / \
4 5 6
\ \
7 8
/ \
9 10
The idea is to recursively traverse the given binary tree and while traversing, maintain “level”
which will store the current node’s level in the tree. If current node is left leaf, then check
if its level is more than the level of deepest left leaf seen so far. If level is more then update
the result. If current node is not leaf, then recursively find maximum depth in left and right
subtrees, and return maximum of the two depths. Thanks to Coder011for suggesting this
approach.
C/C++
// A C++ program to find the deepest left leaf in a given binary tree
#include <stdio.h>
#include <iostream>
using namespace std;
765
Chapter 121. Deepest left leaf node in a binary tree
struct Node
{
int val;
struct Node *left, *right;
};
Node *newNode(int data)
{
Node *temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to find deepest leaf node.
// lvl: level of current node.
// maxlvl: pointer to the deepest left leaf node found so far
// isLeft: A bool indicate that this node is left child of its parent
// resPtr: Pointer to the result
void deepestLeftLeafUtil(Node *root, int lvl, int *maxlvl,
bool isLeft, Node **resPtr)
{
// Base case
if (root == NULL)
return;
// Update result if this node is left leaf and its level is more
// than the maxl level of the current result
if (isLeft && !root->left && !root->right && lvl > *maxlvl)
{
*resPtr = root;
*maxlvl = lvl;
return;
}
// Recur for left and right subtrees
deepestLeftLeafUtil(root->left, lvl+1, maxlvl, true, resPtr);
deepestLeftLeafUtil(root->right, lvl+1, maxlvl, false, resPtr);
}
// A wrapper over deepestLeftLeafUtil().
Node* deepestLeftLeaf(Node *root)
{
int maxlevel = 0;
Node *result = NULL;
deepestLeftLeafUtil(root, 0, &maxlevel, false, &result);
return result;
766
Chapter 121. Deepest left leaf node in a binary tree
}
// Driver program to test above function
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->right = newNode(7);
root->right->right->right = newNode(8);
root->right->left->right->left = newNode(9);
root->right->right->right->right = newNode(10);
Node *result = deepestLeftLeaf(root);
if (result)
cout << "The deepest left child is " << result->val;
else
cout << "There is no left leaf in the given tree";
return 0;
}
Java
767
Chapter 121. Deepest left leaf node in a binary tree
{
// maxlevel: gives the
// value of level of
// maximum left leaf
int maxlevel = 0;
}
class BinaryTree
{
Node root;
// Node to store resultant
// node after left traversal
Node result;
// A utility function to
// find deepest leaf node.
// lvl: level of current node.
// isLeft: A bool indicate
// that this node is left child
void deepestLeftLeafUtil(Node node,
int lvl,
Level level,
boolean isLeft)
{
// Base case
if (node == null)
return;
// Update result if this node
// is left leaf and its level
// is more than the maxl level
// of the current result
if (isLeft != false &&
node.left == null &&
node.right == null &&
lvl > level.maxlevel)
{
result = node;
level.maxlevel = lvl;
}
// Recur for left and right subtrees
deepestLeftLeafUtil(node.left, lvl + 1,
level, true);
deepestLeftLeafUtil(node.right, lvl + 1,
level, false);
}
768
Chapter 121. Deepest left leaf node in a binary tree
// A wrapper over deepestLeftLeafUtil().
void deepestLeftLeaf(Node node)
{
Level level = new Level();
deepestLeftLeafUtil(node, 0, level, false);
}
// Driver program to test above functions
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.right.left = new Node(5);
tree.root.right.right = new Node(6);
tree.root.right.left.right = new Node(7);
tree.root.right.right.right = new Node(8);
tree.root.right.left.right.left = new Node(9);
tree.root.right.right.right.right = new Node(10);
tree.deepestLeftLeaf(tree.root);
if (tree.result != null)
System.out.println("The deepest left child"+
" is " + tree.result.data);
else
System.out.println("There is no left leaf in"+
" the given tree");
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Python
769
Chapter 121. Deepest left leaf node in a binary tree
# A utility function to find deepest leaf node.
# lvl: level of current node.
# maxlvl: pointer to the deepest left leaf node found so far
# isLeft: A bool indicate that this node is left child
# of its parent
# resPtr: Pointer to the result
def deepestLeftLeafUtil(root, lvl, maxlvl, isLeft):
# Base CAse
if root is None:
return
# Update result if this node is left leaf and its
# level is more than the max level of the current result
if(isLeft is True):
if (root.left == None and root.right == None):
if lvl > maxlvl[0] :
deepestLeftLeafUtil.resPtr = root
maxlvl[0] = lvl
return
# Recur for left and right subtrees
deepestLeftLeafUtil(root.left, lvl+1, maxlvl, True)
deepestLeftLeafUtil(root.right, lvl+1, maxlvl, False)
# A wrapper for left and right subtree
def deepestLeftLeaf(root):
maxlvl = [0]
deepestLeftLeafUtil.resPtr = None
deepestLeftLeafUtil(root, 0, maxlvl, False)
return deepestLeftLeafUtil.resPtr
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.left = Node(5)
root.right.right = Node(6)
root.right.left.right = Node(7)
root.right.right.right = Node(8)
root.right.left.right.left = Node(9)
root.right.right.right.right= Node(10)
result = deepestLeftLeaf(root)
770
Chapter 121. Deepest left leaf node in a binary tree
if result is None:
print "There is not left leaf in the given tree"
else:
print "The deepst left child is", result.val
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time Complexity: The function does a simple traversal of the tree, so the complexity is
O(n).
This article is contributed by Abhay Rathi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/deepest-left-leaf-node-in-a-binary-tree/
771
Chapter 122
Input :
1
/ \
2 3
/ / \
4 5 6
\ \
7 8
/ \
9 10
Output : 9
772
Chapter 122. Deepest left leaf node in a binary tree | iterative approach
773
Chapter 122. Deepest left leaf node in a binary tree | iterative approach
}
return result;
}
// driver program
int main()
{
// construct a tree
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->right = newNode(7);
root->right->right->right = newNode(8);
root->right->left->right->left = newNode(9);
root->right->right->right->right = newNode(10);
Node* result = getDeepestLeftLeafNode(root);
if (result)
cout << "Deepest Left Leaf Node :: "
<< result->data << endl;
else
cout << "No result, left leaf not found\n";
return 0;
}
Output:
– Mandeep Singh
Source
https://www.geeksforgeeks.org/deepest-left-leaf-node-binary-tree-iterative-approach/
774
Chapter 123
Input :
1
/ \
2 3
\ / \
4 5 6
\ \
7 8
/ \
9 10
Output : 10
775
Chapter 123. Deepest right leaf node in a binary tree | Iterative approach
776
Chapter 123. Deepest right leaf node in a binary tree | Iterative approach
return result;
}
// driver program
int main()
{
// construct a tree
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->right = newNode(7);
root->right->right->right = newNode(8);
root->right->left->right->left = newNode(9);
root->right->right->right->right = newNode(10);
Node* result = getDeepestRightLeafNode(root);
if (result)
cout << "Deepest Right Leaf Node :: "
<< result->data << endl;
else
cout << "No result, right leaf not found\n";
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/deepest-right-leaf-node-binary-tree-iterative-approach/
777
Chapter 124
Input : x = 5
6
/ \
5 4
/ \ \
1 2 5
Output :
6
/ \
5 4
/ \
1 2
Inorder Traversal is 1 5 2 6 4
778
Chapter 124. Delete leaf nodes with value as x
int data;
struct Node *left, *right;
};
// A utility function to allocate a new node
struct Node* newNode(int data)
{
struct Node* newNode = new Node;
newNode->data = data;
newNode->left = newNode->right = NULL;
return (newNode);
}
Node* deleteLeaves(Node* root, int x)
{
if (root == NULL)
return NULL;
root->left = deleteLeaves(root->left, x);
root->right = deleteLeaves(root->right, x);
if (root->data == x && root->left == NULL &&
root->right == NULL) {
delete(root);
return NULL;
}
return root;
}
void inorder(Node* root)
{
if (root == NULL)
return;
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
// Driver program
int main(void)
{
struct Node* root = newNode(10);
root->left = newNode(3);
root->right = newNode(10);
root->left->left = newNode(3);
root->left->right = newNode(1);
root->right->right = newNode(3);
root->right->right->left = newNode(3);
root->right->right->right = newNode(3);
779
Chapter 124. Delete leaf nodes with value as x
deleteLeaves(root, 3);
cout << "Inorder traversal after deletion : ";
inorder(root);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/delete-leaf-nodes-value-x/
780
Chapter 125
Input : 4
/ \
5 5
/ \ /
3 1 5
Output : 4
/
5
/ \
3 1
781
Chapter 125. Delete leaf nodes with value k
public Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
public class LeafNodesWithValueK {
// Function to delete leaf Node with value
// equal to k
static Node delLeafValueK(Node root, int k)
{
if (root == null)
return null;
root.left = delLeafValueK(root.left, k);
root.right = delLeafValueK(root.right, k);
// If the node is leaf, and its
// value is equal to k
if ((root.left == null &&
root.right == null) &&
root.data == k)
return null;
return root;
}
static void postOrder(Node root)
{
if (root == null)
return;
System.out.print(root.data + " ");
postOrder(root.left);
postOrder(root.right);
}
// Driver Code
public static void main(String[] args)
{
Node root = new Node(4);
root.left = new Node(5);
root.right = new Node(5);
root.left.left = new Node(3);
root.left.right = new Node(1);
782
Chapter 125. Delete leaf nodes with value k
Output:
Source
https://www.geeksforgeeks.org/delete-leaf-nodes-with-value-k/
783
Chapter 126
784
Chapter 126. Deleting a binary tree using the delete keyword
785
Chapter 126. Deleting a binary tree using the delete keyword
delete left;
delete right;
// printing the node which has been deleted
cout << "Deleting " << this->data << endl;
}
};
// Driver Code
int main()
{
// Creating the nodes dynamically
BinaryTreeNode* root = new BinaryTreeNode(1);
BinaryTreeNode* node1 = new BinaryTreeNode(2);
BinaryTreeNode* node2 = new BinaryTreeNode(3);
BinaryTreeNode* node3 = new BinaryTreeNode(4);
BinaryTreeNode* node4 = new BinaryTreeNode(5);
// Creating the binary tree
root->left = node1;
root->right = node2;
node1->left = node3;
node1->right = node4;
// Calls the destructor function which actually deletes the tree entirely
delete root;
return 0;
}
Output:
Deleting 4
Deleting 5
Deleting 2
Deleting 3
Deleting 1
Source
https://www.geeksforgeeks.org/deleting-a-binary-tree-using-the-delete-keyword/
786
Chapter 127
Algorithm
1. Starting at root, find the deepest and rightmost node in binary tree and node which we
787
Chapter 127. Deletion in a Binary Tree
want to delete.
2. Replace the deepest rightmost node’s data with node to be deleted.
3. Then delete the deepest rightmost node.
788
Chapter 127. Deletion in a Binary Tree
/* function to create a new node of tree and
return pointer */
struct Node* newNode(int key)
{
struct Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
};
/* Inorder traversal of a binary tree*/
void inorder(struct Node* temp)
{
if (!temp)
return;
inorder(temp->left);
cout << temp->key << " ";
inorder(temp->right);
}
/* function to delete the given deepest node
(d_node) in binary tree */
void deletDeepest(struct Node *root,
struct Node *d_node)
{
queue<struct Node*> q;
q.push(root);
// Do level order traversal until last node
struct Node* temp;
while(!q.empty())
{
temp = q.front();
q.pop();
if (temp->right)
{
if (temp->right == d_node)
{
temp->right = NULL;
delete(d_node);
return;
}
else
q.push(temp->right);
}
789
Chapter 127. Deletion in a Binary Tree
if (temp->left)
{
if (temp->left == d_node)
{
temp->left=NULL;
delete(d_node);
return;
}
else
q.push(temp->left);
}
}
}
/* function to delete element in binary tree */
void deletion(struct Node* root, int key)
{
queue<struct Node*> q;
q.push(root);
struct Node *temp;
struct Node *key_node = NULL;
// Do level order traversal to find deepest
// node(temp) and node to be deleted (key_node)
while (!q.empty())
{
temp = q.front();
q.pop();
if (temp->key == key)
key_node = temp;
if (temp->left)
q.push(temp->left);
if (temp->right)
q.push(temp->right);
}
int x = temp->key;
deletDeepest(root, temp);
key_node->key = x;
}
// Driver code
int main()
{
790
Chapter 127. Deletion in a Binary Tree
Output:
Note: We can also replace node’s data that is to be deleted with any node whose left and
right child points to NULL but we only use deepest node in order to maintain the Balance
of a binary tree.
Improved By : programmer2k17
Source
https://www.geeksforgeeks.org/deletion-binary-tree/
791
Chapter 128
Examples:
Output: 1.5
Height of given tree = 2
Size of given tree = 3
792
Chapter 128. Density of Binary Tree in One Traversal
Density of a Binary Tree indicates, how balanced Binary Tree is. For example density of a
skewed tree is minimum and that of a perfect tree is maximum.
We strongly recommend you to minimize your browser and try this yourself
first.
Two traversal based approach is very simple. First find the height using one traversal, then
find the size using another traversal. Finally return the ratio of two values.
To do it in one traversal, we compute size of Binary Tree while finding its height. Below is
C++ implementation.
C++
793
Chapter 128. Density of Binary Tree in One Traversal
return (l > r) ? l + 1 : r + 1;
}
//function to calculate density of a binary tree
float density(Node* root)
{
if (root == NULL)
return 0;
int size = 0; // To store size
// Finds height and size
int _height = heighAndSize(root, size);
return (float)size/_height;
}
// Driver code to test above methods
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
printf("Density of given binary tree is %f",
density(root));
return 0;
}
Java
794
Chapter 128. Density of Binary Tree in One Traversal
class Size
{
// variable to calculate size of tree
int size = 0;
}
class BinaryTree
{
Node root;
// Function to compute height and
// size of a binary tree
int heighAndSize(Node node, Size size)
{
if (node == null)
return 0;
// compute height of each subtree
int l = heighAndSize(node.left, size);
int r = heighAndSize(node.right, size);
//increase size by 1
size.size++;
//return larger of the two
return (l > r) ? l + 1 : r + 1;
}
//function to calculate density of a binary tree
float density(Node root)
{
Size size = new Size();
if (root == null)
return 0;
// Finds height and size
int _height = heighAndSize(root, size);
return (float) size.size / _height;
}
// Driver code to test above methods
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
795
Chapter 128. Density of Binary Tree in One Traversal
System.out.println("Density of given Binary Tree is : "
+ tree.density(tree.root));
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output:
Reference:
http://www.eem.anadolu.edu.tr/egermen/EEM%20480/icerik/EEM%20480%20Algorithms%
20and%20Complexity%20Week%208.pdf
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/density-of-binary-tree-in-one-traversal/
796
Chapter 129
Example 2:
797
Chapter 129. Depth of an N-Ary tree
N-Ary tree can be traversed just like a normal tree. We just have to consider all childs of a
given node and recursively call that function on every node.
798
Chapter 129. Depth of an N-Ary tree
return 0;
// Check for all children and find
// the maximum depth
int maxdepth = 0;
for (vector<Node*>::iterator it = ptr->child.begin();
it != ptr->child.end(); it++)
maxdepth = max(maxdepth, depthOfTree(*it));
return maxdepth + 1 ;
}
// Driver program
int main()
{
/* Let us create below tree
* A
* / / \ \
* B F D E
* / \ | /|\
* K J G C H I
* /\ \
* N M L
*/
Node *root = newNode('A');
(root->child).push_back(newNode('B'));
(root->child).push_back(newNode('F'));
(root->child).push_back(newNode('D'));
(root->child).push_back(newNode('E'));
(root->child[0]->child).push_back(newNode('K'));
(root->child[0]->child).push_back(newNode('J'));
(root->child[2]->child).push_back(newNode('G'));
(root->child[3]->child).push_back(newNode('C'));
(root->child[3]->child).push_back(newNode('H'));
(root->child[3]->child).push_back(newNode('I'));
(root->child[0]->child[0]->child).push_back(newNode('N'));
(root->child[0]->child[0]->child).push_back(newNode('M'));
(root->child[3]->child[2]->child).push_back(newNode('L'));
cout << depthOfTree(root) << endl;
return 0;
}
Output:
799
Chapter 129. Depth of an N-Ary tree
Source
https://www.geeksforgeeks.org/depth-n-ary-tree/
800
Chapter 130
Input :
Output : 5
Input : 10
/ \
28 13
/ \
14 15
/ \
23 24
Output : 3
We can traverse the tree starting from the root level and keep curr_level of the node.
Increment the curr_level each time we go to left or a right subtree.
Return the max depth of an odd level,if it exists.
Algorithm:
801
Chapter 130. Depth of the deepest odd level node in Binary Tree
802
Chapter 130. Depth of the deepest odd level node in Binary Tree
curr_level += 1;
// if curr_level is odd
// and its a leaf node
if ( curr_level % 2 != 0 && isleaf(curr_node))
return curr_level;
return max(deepestOddLevelDepthUtil(curr_node->left,curr_level),
deepestOddLevelDepthUtil(curr_node->right,curr_level));
}
// A wrapper over deepestOddLevelDepth()
int deepestOddLevelDepth(Node *curr_node)
{
return deepestOddLevelDepthUtil(curr_node, 0);
}
int main()
{
/* 10
/ \
28 13
/ \
14 15
/ \
23 24
Let us create Binary Tree shown in above example */
Node *root = newNode(10);
root->left = newNode(28);
root->right = newNode(13);
root->right->left = newNode(14);
root->right->right = newNode(15);
root->right->right->left = newNode(23);
root->right->right->right = newNode(24);
cout << deepestOddLevelDepth(root) << endl;
return 0;
}
Output:
803
Chapter 130. Depth of the deepest odd level node in Binary Tree
Source
https://www.geeksforgeeks.org/depth-deepest-odd-level-node-binary-tree/
804
Chapter 131
Algorithm:
The idea is to keep track of vertical distance from top diagonal passing through root. We
increment the vertical distance we go down to next diagonal.
1. Add root with vertical distance as 0 to the queue.
2. Process the sum of all right child and right of right child and so on.
3. Add left child current node into the queue for later processing. The vertical distance of
805
Chapter 131. Diagonal Sum of a Binary Tree
806
Chapter 131. Diagonal Sum of a Binary Tree
}
// Function to calculate diagonal
// sum of given binary tree
void diagonalSum(struct Node* root)
{
// create a map to store Diagonal Sum
map<int, int> diagonalSum;
diagonalSumUtil(root, 0, diagonalSum);
map<int, int>::iterator it;
cout << "Diagonal sum in a binary tree is - ";
for(it = diagonalSum.begin();
it != diagonalSum.end(); ++it)
{
cout << it->second << " ";
}
}
// Driver code
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(9);
root->left->right = newNode(6);
root->right->left = newNode(4);
root->right->right = newNode(5);
root->right->left->right = newNode(7);
root->right->left->left = newNode(12);
root->left->right->left = newNode(11);
root->left->left->right = newNode(10);
diagonalSum(root);
return 0;
}
// This code is contributed by Aditya Goel
Java
807
Chapter 131. Diagonal Sum of a Binary Tree
import java.util.Map.Entry;
//Tree node
class TreeNode
{
int data; //node data
int vd; //vertical distance diagonally
TreeNode left, right; //left and right child's reference
// Tree node constructor
public TreeNode(int data)
{
this.data = data;
vd = Integer.MAX_VALUE;
left = right = null;
}
}
// Tree class
class Tree
{
TreeNode root;//Tree root
// Tree constructor
public Tree(TreeNode root) { this.root = root; }
// Diagonal sum method
public void diagonalSum()
{
// Queue which stores tree nodes
Queue<TreeNode> queue = new LinkedList<TreeNode>();
// Map to store sum of node's data lying diagonally
Map<Integer, Integer> map = new TreeMap<>();
// Assign the root's vertical distance as 0.
root.vd = 0;
// Add root node to the queue
queue.add(root);
// Loop while the queue is not empty
while (!queue.isEmpty())
{
// Remove the front tree node from queue.
TreeNode curr = queue.remove();
// Get the vertical distance of the dequeued node.
808
Chapter 131. Diagonal Sum of a Binary Tree
int vd = curr.vd;
// Sum over this node's right-child, right-of-right-child
// and so on
while (curr != null)
{
int prevSum = (map.get(vd) == null)? 0: map.get(vd);
map.put(vd, prevSum + curr.data);
// If for any node the left child is not null add
// it to the queue for future processing.
if (curr.left != null)
{
curr.left.vd = vd+1;
queue.add(curr.left);
}
// Move to the current node's right child.
curr = curr.right;
}
}
// Make an entry set from map.
Set<Entry<Integer, Integer>> set = map.entrySet();
// Make an iterator
Iterator<Entry<Integer, Integer>> iterator = set.iterator();
// Traverse the map elements using the iterator.
System.out.print("Diagonal sum in a binary tree is - ");
while (iterator.hasNext())
{
Map.Entry<Integer, Integer> me = iterator.next();
System.out.print(me.getValue()+" ");
}
}
}
//Driver class
public class DiagonalSum
{
public static void main(String[] args)
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(9);
809
Chapter 131. Diagonal Sum of a Binary Tree
Output:
Exercise:
This problem was for diagonals from top to bottom and slope -1. Try the same problem for
slope +1.
This article is contributed by Kumar Gautam. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/diagonal-sum-binary-tree/
810
Chapter 132
Output :
Diagonal Traversal of binary tree :
8 10 14
3 6 7 13
1 4
The idea is to use map. We use different slope distances and use them as key in map. Value
in map is vector (or dynamic array) of nodes. We traverse the tree to store values in map.
Once map is built, we print contents of it.
Below is implementation of above idea.
C++
811
Chapter 132. Diagonal Traversal of Binary Tree
int data;
Node *left, *right;
};
/* root - root of the binary tree
d - distance of current line from rightmost
-topmost slope.
diagonalPrint - multimap to store Diagonal
elements (Passed by Reference) */
void diagonalPrintUtil(Node* root, int d,
map<int, vector<int>> &diagonalPrint)
{
// Base case
if (!root)
return;
// Store all nodes of same line together as a vector
diagonalPrint[d].push_back(root->data);
// Increase the vertical distance if left child
diagonalPrintUtil(root->left, d + 1, diagonalPrint);
// Vertical distance remains same for right child
diagonalPrintUtil(root->right, d, diagonalPrint);
}
// Print diagonal traversal of given binary tree
void diagonalPrint(Node* root)
{
// create a map of vectors to store Diagonal elements
map<int, vector<int> > diagonalPrint;
diagonalPrintUtil(root, 0, diagonalPrint);
cout << "Diagonal Traversal of binary tree : n";
for (auto it = diagonalPrint.begin();
it != diagonalPrint.end(); ++it)
{
for (auto itr = it->second.begin();
itr != it->second.end(); ++itr)
cout << *itr << ' ';
cout << 'n';
}
}
// Utility method to create a new node
Node* newNode(int data)
{
812
Chapter 132. Diagonal Traversal of Binary Tree
Java
813
Chapter 132. Diagonal Traversal of Binary Tree
Node left;
Node right;
//constructor
Node(int data)
{
this.data=data;
left = null;
right =null;
}
}
/* root - root of the binary tree
d - distance of current line from rightmost
-topmost slope.
diagonalPrint - HashMap to store Diagonal
elements (Passed by Reference) */
static void diagonalPrintUtil(Node root,int d,
HashMap<Integer,Vector<Integer>> diagonalPrint){
// Base case
if (root == null)
return;
// get the list at the particular d value
Vector<Integer> k = diagonalPrint.get(d);
// k is null then create a vector and store the data
if (k == null)
{
k = new Vector<>();
k.add(root.data);
}
// k is not null then update the list
else
{
k.add(root.data);
}
// Store all nodes of same line together as a vector
diagonalPrint.put(d,k);
// Increase the vertical distance if left child
diagonalPrintUtil(root.left, d + 1, diagonalPrint);
// Vertical distance remains same for right child
diagonalPrintUtil(root.right, d, diagonalPrint);
814
Chapter 132. Diagonal Traversal of Binary Tree
}
// Print diagonal traversal of given binary tree
static void diagonalPrint(Node root)
{
// create a map of vectors to store Diagonal elements
HashMap<Integer,Vector<Integer>> diagonalPrint = new HashMap<>();
diagonalPrintUtil(root, 0, diagonalPrint);
System.out.println("Diagonal Traversal of Binnary Tree");
for (Entry<Integer, Vector<Integer>> entry : diagonalPrint.entrySet())
{
System.out.println(entry.getValue());
}
}
// Driver program
public static void main(String[] args) {
Node root = new Node(8);
root.left = new Node(3);
root.right = new Node(10);
root.left.left = new Node(1);
root.left.right = new Node(6);
root.right.right = new Node(14);
root.right.right.left = new Node(13);
root.left.right.left = new Node(4);
root.left.right.right = new Node(7);
diagonalPrint(root);
}
}
// This code is contributed by Sumit Ghosh
Python
815
Chapter 132. Diagonal Traversal of Binary Tree
816
Chapter 132. Diagonal Traversal of Binary Tree
root.right.right.left = Node(13)
root.left.right.left = Node(4)
root.left.right.right = Node(7)
diagonalPrint(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output :
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : Sachin Verma 7
Source
https://www.geeksforgeeks.org/diagonal-traversal-of-binary-tree/
817
Chapter 133
818
Chapter 133. Diameter of a Binary Tree
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left, *right;
};
/* function to create a new node of tree and returns pointer */
struct node* newNode(int data);
/* returns max of two integers */
int max(int a, int b);
/* function to Compute height of a tree. */
int height(struct node* node);
/* Function to get diameter of a binary tree */
int diameter(struct node * tree)
{
/* base case where tree is empty */
if (tree == NULL)
return 0;
/* get the height of left and right sub-trees */
int lheight = height(tree->left);
int rheight = height(tree->right);
/* get the diameter of left and right sub-trees */
int ldiameter = diameter(tree->left);
int rdiameter = diameter(tree->right);
/* Return max of following three
1) Diameter of left subtree
2) Diameter of right subtree
3) Height of left subtree + height of right subtree + 1 */
return max(lheight + rheight + 1, max(ldiameter, rdiameter));
}
/* UTILITY FUNCTIONS TO TEST diameter() FUNCTION */
/* The function Compute the "height" of a tree. Height is the
number f nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
819
Chapter 133. Diameter of a Binary Tree
{
/* base case tree is empty */
if(node == NULL)
return 0;
/* If tree is not empty then height = 1 + max of left
height and right heights */
return 1 + max(height(node->left), height(node->right));
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* returns maximum of two integers */
int max(int a, int b)
{
return (a >= b)? a: b;
}
/* Driver program to test above functions*/
int main()
{
/* Constructed binary tree is
1
/ \
2 3
/ \
4 5
*/
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Diameter of the given binary tree is %d\n", diameter(root));
820
Chapter 133. Diameter of a Binary Tree
getchar();
return 0;
}
Java
821
Chapter 133. Diameter of a Binary Tree
Math.max(ldiameter, rdiameter));
}
/* A wrapper over diameter(Node root) */
int diameter()
{
return diameter(root);
}
/*The function Compute the "height" of a tree. Height is the
number f nodes along the longest path from the root node
down to the farthest leaf node.*/
static int height(Node node)
{
/* base case tree is empty */
if (node == null)
return 0;
/* If tree is not empty then height = 1 + max of left
height and right heights */
return (1 + Math.max(height(node.left), height(node.right)));
}
public static void main(String args[])
{
/* creating a binary tree and entering the nodes */
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("The diameter of given binary tree is : "
+ tree.diameter());
}
}
Python
822
Chapter 133. Diameter of a Binary Tree
self.data = data
self.left = None
self.right = None
"""
The function Compute the "height" of a tree. Height is the
number f nodes along the longest path from the root node
down to the farthest leaf node.
"""
def height(node):
# Base Case : Tree is empty
if node is None:
return 0 ;
# If tree is not empty then height = 1 + max of left
# height and right heights
return 1 + max(height(node.left) ,height(node.right))
# Function to get the diamtere of a binary tree
def diameter(root):
# Base Case when tree is empty
if root is None:
return 0;
# Get the height of left and right sub-trees
lheight = height(root.left)
rheight = height(root.right)
# Get the diameter of left and irgh sub-trees
ldiameter = diameter(root.left)
rdiameter = diameter(root.right)
# Return max of the following tree:
# 1) Diameter of left subtree
# 2) Diameter of right subtree
# 3) Height of left subtree + height of right subtree +1
return max(lheight + rheight + 1, max(ldiameter, rdiameter))
# Driver program to test above functions
"""
Constructed binary tree is
1
/ \
823
Chapter 133. Diameter of a Binary Tree
2 3
/ \
4 5
"""
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "Diameter of given binary tree is %d" %(diameter(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
824
Chapter 133. Diameter of a Binary Tree
/* Get the heights of left and right subtrees in lh and rh
And store the returned values in ldiameter and ldiameter */
ldiameter = diameterOpt(root->left, &lh);
rdiameter = diameterOpt(root->right, &rh);
/* Height of current node is max of heights of left and
right subtrees plus 1*/
*height = max(lh, rh) + 1;
return max(lh + rh + 1, max(ldiameter, rdiameter));
}
Java
825
Chapter 133. Diameter of a Binary Tree
826
Chapter 133. Diameter of a Binary Tree
References:
http://www.cs.duke.edu/courses/spring00/cps100/assign/trees/diameter.html
Source
https://www.geeksforgeeks.org/diameter-of-a-binary-tree/
827
Chapter 134
Examples:
Input : 1
828
Chapter 134. Diameter of a Binary Tree in O(n) [A new method]
/ \
2 3
/ \
4 5
Output : 4
Input : 1
/ \
2 3
/ \ . \
4 5 . 6
Output : 5
829
Chapter 134. Diameter of a Binary Tree in O(n) [A new method]
Output:
Diameter is 4
Source
https://www.geeksforgeeks.org/diameter-of-a-binary-tree-in-on-a-new-method/
830
Chapter 135
831
Chapter 135. Diameter of a tree using DFS
and check the farthest node from it, we will get the diameter of the tree.
The C++ implementation uses adjacency list representation of graphs. STL‘s list container
is used to store lists of adjacent nodes.
C++
832
Chapter 135. Diameter of a tree using DFS
Java
833
Chapter 135. Diameter of a tree using DFS
834
Chapter 135. Diameter of a tree using DFS
}
// Returns diameter of binary tree represented
// as adjacency list.
static int diameter(List<Integer> adj[], int n)
{
maxCount = Integer.MIN_VALUE;
/* DFS from a random node and then see
farthest node X from it*/
dfs(1, n, adj);
/* DFS from X and check the farthest node
from it */
dfs(x, n, adj);
return maxCount;
}
/* Driver program to test above functions*/
public static void main(String args[])
{
int n = 5;
/* Constructed tree is
1
/ \
2 3
/ \
4 5 */
adj = new List[n + 1];
for(int i = 0; i < n+1 ; i++)
adj[i] = new ArrayList<Integer>();
/*create undirected edges */
adj[1].add(2);
adj[2].add(1);
adj[1].add(3);
adj[3].add(1);
adj[2].add(4);
adj[4].add(2);
adj[2].add(5);
adj[5].add(2);
/* maxCount will have diameter of tree */
System.out.println("Diameter of the given " +
"tree is " + diameter(adj, n));
}
835
Chapter 135. Diameter of a tree using DFS
}
// This code is contributed by Sumit Ghosh
Output:
Source
https://www.geeksforgeeks.org/diameter-tree-using-dfs/
836
Chapter 136
Example 2:
837
Chapter 136. Diameter of an N-ary tree
838
Chapter 136. Diameter of an N-ary tree
839
Chapter 136. Diameter of an N-ary tree
Output:
840
Chapter 136. Diameter of an N-ary tree
We can make a hash table to store heights of all nodes. If we precompute these heights, we
don’t need to call depthOfTree() for every node.
A different optimized solution :
Longest path in an undirected tree
Source
https://www.geeksforgeeks.org/diameter-n-ary-tree/
841
Chapter 137
Step 1: Run bfs to find the farthest node from rooted tree let say A
Step 2: Then run bfs from A to find farthest node from A let B
Step 3: Distance between node A and B is the diameter of given tree
842
Chapter 137. Diameter of n-ary tree using BFS
#include <bits/stdc++.h>
using namespace std;
// Here 10000 is maximum number of nodes in
// given tree.
int diameter[10001];
// The Function to do bfs traversal.
// It uses iterative approach to do bfs
// bfsUtil()
int bfs(int init, vector<int> arr[], int n)
{
// Initializing queue
queue<int> q;
q.push(init);
int visited[n + 1];
for (int i = 0; i <= n; i++) {
visited[i] = 0;
diameter[i] = 0;
}
// Pushing each node in queue
q.push(init);
// Mark the traversed node visited
visited[init] = 1;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = 0; i < arr[u].size(); i++) {
if (visited[arr[u][i]] == 0) {
visited[arr[u][i]] = 1;
// Considering weight of edges equal to 1
diameter[arr[u][i]] += diameter[u] + 1;
q.push(arr[u][i]);
}
}
}
// return index of max value in diameter
return int(max_element(diameter + 1,
diameter + n + 1)
- diameter);
}
int findDiameter(vector<int> arr[], int n)
843
Chapter 137. Diameter of n-ary tree using BFS
{
int init = bfs(1, arr, n);
int val = bfs(init, arr, n);
return diameter[val];
}
// Driver Code
int main()
{
// Input number of nodes
int n = 6;
vector<int> arr[n + 1];
// Input nodes in adjacency list
arr[1].push_back(2);
arr[1].push_back(3);
arr[1].push_back(6);
arr[2].push_back(4);
arr[2].push_back(1);
arr[2].push_back(5);
arr[3].push_back(1);
arr[4].push_back(2);
arr[5].push_back(2);
arr[6].push_back(1);
printf("Diameter of n-ary tree is %d\n",
findDiameter(arr, n));
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/diameter-n-ary-tree-using-bfs/
844
Chapter 138
Difference between sums of odd level and even level nodes of a Binary Tree - GeeksforGeeks
Given a a Binary Tree, find the difference between the sum of nodes at odd level and the
sum of nodes at even level. Consider root as level 1, left and right children of root as level
2 and so on.
For example, in the following tree, sum of nodes at odd level is (5 + 1 + 4 + 8) which is
18. And sum of nodes at even level is (2 + 6 + 3 + 7 + 9) which is 27. The output for
following tree should be 18 – 27 which is -9.
5
/ \
2 6
/ \ \
1 4 8
/ / \
3 7 9
A straightforward method is to use level order traversal. In the traversal, check level of
current node, if it is odd, increment odd sum by data of current node, otherwise increment
even sum. Finally return difference between odd sum and even sum. See following for
implementation of this approach.
C implementation of level order traversal based approach to find the difference.
This approach is provided by Mandeep Singh. For Iterative approach, simply traverse
the tree level by level (level order traversal), store sum of node values in even no. level in
evenSum and rest in variable oddSum and finally return the difference.
845
Chapter 138. Difference between sums of odd level and even level nodes of a Binary Tree
C++
846
Chapter 138. Difference between sums of odd level and even level nodes of a Binary Tree
{
int size = q.size();
level += 1;
// traverse for
// complete level
while(size > 0)
{
Node* temp = q.front();
q.pop();
// check if level no.
// is even or odd and
// accordingly update
// the evenSum or oddSum
if(level % 2 == 0)
evenSum += temp->data;
else
oddSum += temp->data;
// check for left child
if (temp->left)
{
q.push(temp->left);
}
// check for right child
if (temp->right)
{
q.push(temp->right);
}
size -= 1;
}
}
return (oddSum - evenSum);
}
// driver program
int main()
{
// construct a tree
Node* root = newNode(5);
root->left = newNode(2);
root->right = newNode(6);
root->left->left = newNode(1);
root->left->right = newNode(4);
root->left->right->left = newNode(3);
847
Chapter 138. Difference between sums of odd level and even level nodes of a Binary Tree
root->right->right = newNode(8);
root->right->right->right = newNode(9);
root->right->right->left = newNode(7);
int result = evenOddLevelDifference(root);
cout << "diffence between sums is :: ";
cout << result << endl;
return 0;
}
// This article is contributed by Mandeep Singh.
The problem can also be solved using simple recursive traversal. We can recursively
calculate the required difference as, value of root’s data subtracted by the difference for
subtree under left child and the difference for subtree under right child.
Below is the implementation of this approach.
C
848
Chapter 138. Difference between sums of odd level and even level nodes of a Binary Tree
Java
849
Chapter 138. Difference between sums of odd level and even level nodes of a Binary Tree
{
// Base case
if (node == null)
return 0;
// Difference for root is root's data - difference for
// left subtree - difference for right subtree
return node.data - getLevelDiff(node.left) -
getLevelDiff(node.right);
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(5);
tree.root.left = new Node(2);
tree.root.right = new Node(6);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(4);
tree.root.left.right.left = new Node(3);
tree.root.right.right = new Node(8);
tree.root.right.right.right = new Node(9);
tree.root.right.right.left = new Node(7);
System.out.println(tree.getLevelDiff(tree.root) +
" is the required difference");
}
}
// This code has been contributed by Mayank Jaiswal
Python
850
Chapter 138. Difference between sums of odd level and even level nodes of a Binary Tree
def getLevelDiff(root):
# Base Case
if root is None:
return 0
# Difference for root is root's data - difference for
# left subtree - difference for right subtree
return (root.data - getLevelDiff(root.left)-
getLevelDiff(root.right))
# Driver program to test above function
root = Node(5)
root.left = Node(2)
root.right = Node(6)
root.left.left = Node(1)
root.left.right = Node(4)
root.left.right.left = Node(3)
root.right.right = Node(8)
root.right.right.right = Node(9)
root.right.right.left = Node(7)
print "%d is the required difference" %(getLevelDiff(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time complexity of both methods is O(n), but the second method is simple and easy to
implement.
This article is contributed by Chandra Prakash. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/difference-between-sums-of-odd-and-even-levels/
851
Chapter 139
Approach :We can find solution by simply running DFS on tree. DFS solution gives us
answer in O(n). But, how can we use DSU for this problem? We first iterate through all
852
Chapter 139. Disjoint Set Union on trees | Set 1
edges. If both nodes are even in weights, we make union of them. Set of nodes with maximum
size is the answer. If we use union-find with path compression then time complexity is O(n).
Below is the implementation of above approach :
853
Chapter 139. Disjoint Set Union on trees | Set 1
{
id[i] = j, sz[j] += sz[i];
sz[i] = 0;
}
}
}
// Utility function for Union
void UnionUtil(struct Edge e[], int W[], int q)
{
for(int i = 0; i < q; i++)
{
// Edge between 'u' and 'v'
int u, v;
u = e[i].u, v = e[i].v;
// 0-indexed nodes
u--, v--;
// If weights of both 'u' and 'v'
// are even then we make union of them.
if(W[u] % 2 == 0 && W[v] % 2 == 0)
Union(u,v);
}
}
// Function to find maximum
// size of DSU tree
int findMax(int n, int W[])
{
int maxi = 0;
for(int i = 1; i <= n; i++)
if(W[i] % 2 == 0)
maxi = max(maxi, sz[i]);
return maxi;
}
// Driver code
int main()
{
/*
Nodes are 0-indexed in this code
So we have to make necessary changes
while taking inputs
*/
854
Chapter 139. Disjoint Set Union on trees | Set 1
Output:
Source
https://www.geeksforgeeks.org/disjoint-set-union-trees-set-1/
855
Chapter 140
Approach : The strategy is to fix the AND, and find the maximum size of a subtree such
that AND of all indices equals to the given AND. Suppose we fix AND as ‘A’. In binary
representation of A, if the ith bit is ‘1’, then all indices(nodes) of the required subtree should
have ‘1’ in ith position in binary representation. If ith bit is ‘0’ then indices either have ‘0’
or ‘1’ in ith position. That means all elements of subtree are super masks of A. All super
masks of A can be generated in O(2^k) time where ‘k’ is the number of bits which are ‘0’
in A.
856
Chapter 140. Disjoint Set Union on trees | Set 2
Now, the maximum size of subtree with a given AND ‘A’ can be found using DSU on the
tree. Let, ‘u’ be the super mask of A and ‘p[u]’ be the parent of u. If p[u] is also a super
mask of A, then, we have to update the DSU by merging the components of u and p[u].
Simultaneously, we also have to keep track of the maximum size of subtree. DSU helps us
to do it. It will be more clear if we look at following code.
857
Chapter 140. Disjoint Set Union on trees | Set 2
else {
id[i] = j, sz[j] += sz[i];
sz[i] = 0;
}
}
}
};
wunionfind W;
// DFS is called to generate parent of
// a node from adjacency list representation
void dfs(int u, int parent)
{
for (int i = 0; i < v[u].size(); i++) {
int j = v[u][i];
if (j != parent) {
p[j] = u;
dfs(j, u);
}
}
}
// Utility function for Union
int UnionUtil(int n)
{
int ans = 0;
// Fixed 'i' as AND
for (int i = 1; i <= n; i++) {
int maxi = 1;
// Generating supermasks of 'i'
for (int x = i; x <= n; x = (i | (x + 1))) {
int y = p[x];
// Checking whether p[x] is
// also a supermask of i.
if ((y & i) == i) {
W.Union(x, y);
// Keep track of maximum
// size of subtree
maxi = max(maxi, W.sz[W.Root(x)]);
}
}
// Storing maximum cost of
858
Chapter 140. Disjoint Set Union on trees | Set 2
859
Chapter 140. Disjoint Set Union on trees | Set 2
return 0;
}
Output:
Maximum Cost = 8
Time Complexity : Union in DSU takes O(1) time. Generating all supermasks takes
O(3^k) time where k is the maximum number of bits which are ‘0’. DFS takes O(n). Overall
time complexity is O(3^k+n).
Source
https://www.geeksforgeeks.org/disjoint-set-union-trees-set-2/
860
Chapter 141
Double Tree
2
/ \
1 3
is changed to…
2
/ \
2 3
/ /
1 3
/
1
1
/ \
2 3
/ \
4 5
is changed to
861
Chapter 141. Double Tree
1
/ \
1 3
/ /
2 3
/ \
2 5
/ /
4 5
/
4
Algorithm:
Recursively convert the tree to double tree in postorder fashion. For each node, first convert
the left subtree of the node, then right subtree, finally create a duplicate node of the node
and fix the left child of the node and left child of left child.
Implementation:
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* function to create a new node of tree and returns pointer */
struct node* newNode(int data);
/* Function to convert a tree to double tree */
void doubleTree(struct node* node)
{
struct node* oldLeft;
if (node==NULL) return;
/* do the subtrees */
doubleTree(node->left);
doubleTree(node->right);
862
Chapter 141. Double Tree
863
Chapter 141. Double Tree
root->left->right = newNode(5);
printf("Inorder traversal of the original tree is \n");
printInorder(root);
doubleTree(root);
printf("\n Inorder traversal of the double tree is \n");
printInorder(root);
getchar();
return 0;
}
Java
864
Chapter 141. Double Tree
865
Chapter 141. Double Tree
Source
https://www.geeksforgeeks.org/double-tree/
866
Chapter 142
Dynamic Programming on
Trees | Set 2
The above diagram represents a tree with 11 nodes and 10 edges, and the path which
gives us the maximum height when node 1 is considered as root. The maximum height is 3.
867
Chapter 142. Dynamic Programming on Trees | Set 2
In the above diagram, when 2 is considered as root, then the longest path found is in RED
color. A naive approach will be to traverse the tree using DFS traversal for every node
and calculate the maximum height when the node is treated as the root of the tree. The
time complexity for DFS traversal of a tree is O(N). The overall time complexity of
DFS for all N nodes will be O(N)*N i.e., O(N2 ).
The above problem can be solved by using Dynamic Programming on Trees. To solve
this problem, pre-calculate two things for every node. One will be the maximum height while
traveling downwards via its branches to the leaves. While the other will be the maximum
height when traveling upwards via its parent to any of the leaves.
Optimal Substructure :
When node i is considered as root,
in[i] be the maximum height of tree when we travel downwards via its sub-trees and leaves.
Also, out[i] be the maximum height of the tree while traveling upwards via its parent.
Calculation of in[i] :
868
Chapter 142. Dynamic Programming on Trees | Set 2
In the image above, values of in[i] have been calculated for every node i. The maximum of
every subtree is taken and added with 1 to the parent of that subtree. Add 1 for the edge
between parent and subtree. Traverse the tree using DFS and calculate in[i] as max(in[i],
1+in[child]) for every node.
Calculation of out[i] :
The above diagram shows all the out[i] values and the path. For calculation of out[i], move
upwards to the parent of node i. From the parent of node i, there are two ways to move in,
one will be in all the branches of the parent. The other direction is to move to the parent(call
it parent2 to avoid confusion) of the parent(call it parent1) of node i. The maximum height
upwards via parent2 is out[parent1] itself. Generally, out[node i] as 1+max(out[i], 1+max
869
Chapter 142. Dynamic Programming on Trees | Set 2
of all branches). Add 1 for the edges between node and parent.
The above diagram explains the calculation of out[i] when 2 is considered as the root of the
tree. The branches of node 2 is not taken into count since the maximum height via that
path has already been calculated and stored in i[2]. Moving up, in this case, the parent of 2
i.e., 1 has no parent. So, the branches except for the one which has the node are considered
while calculating the maximum.
The above diagram explains the calculation of out[10]. The parent of node 10, i.e., 7 has
a parent and a branch(precisely a child in this case). So the maximum height of both has
been taken to count in such cases when parent and branches exist.
870
Chapter 142. Dynamic Programming on Trees | Set 2
C++
871
Chapter 142. Dynamic Programming on Trees | Set 2
872
Chapter 142. Dynamic Programming on Trees | Set 2
}
// fucntion to print all the maximum heights
// from every node
void printHeights(vector<int> v[], int n)
{
// traversal to calculate in[] array
dfs1(v, 1, 0);
// traversal to calculate out[] array
dfs2(v, 1, 0);
// print all maximum heights
for (int i = 1; i <= n; i++)
cout << "The maximum height when node "
<< i << " is considered as root"
<< " is " << max(in[i], out[i])
<< "\n";
}
// Driver Code
int main()
{
int n = 11;
vector<int> v[n + 1];
// initialize the tree given in the diagram
v[1].push_back(2), v[2].push_back(1);
v[1].push_back(3), v[3].push_back(1);
v[1].push_back(4), v[4].push_back(1);
v[2].push_back(5), v[5].push_back(2);
v[2].push_back(6), v[6].push_back(2);
v[3].push_back(7), v[7].push_back(3);
v[7].push_back(10), v[10].push_back(7);
v[7].push_back(11), v[11].push_back(7);
v[4].push_back(8), v[8].push_back(4);
v[4].push_back(9), v[9].push_back(4);
// function to print the maximum height from every node
printHeights(v, n);
return 0;
}
Output :
873
Chapter 142. Dynamic Programming on Trees | Set 2
Source
https://www.geeksforgeeks.org/dynamic-programming-trees-set-2/
874
Chapter 143
Dynamic Programming on
Trees | Set-1
875
Chapter 143. Dynamic Programming on Trees | Set-1
Given above is a diagram of a tree with N=14 nodes and N-1=13 edges. The values at
node being 3, 2, 1, 10, 1, 3, 9, 1, 5, 3, 4, 5, 9 and 8 respectively for nodes 1, 2, 3,
4….14.
The diagram below shows all the paths from root to leaves :
876
Chapter 143. Dynamic Programming on Trees | Set-1
first level, 10 from the next level and 5 from the third level greedily. Result is path-7 if after
following greedy approach, hence do not apply greedy approach over here.
The problem can be solved using Dynamic Programming on trees. Start memoizing
from the leaves and add the maximum of leaves to the root of every sub-tree. At the last
step, there will be root and the sub-tree under it, adding the value at node and maximum
of sub-tree will give us the maximum sum of the node values from root to any of the leaves.
The diagram above shows how to start from the leaves and add the maximum of
leaves of a sub-tree to its root. Move upward and repeat the same procedure of storing
the maximum of every sub-tree leaves and adding it to its root. In this example, the
maximum of node 11 and 12 is taken to count and then added to node 5(In this sub-tree,
5 is the root and 11, 12 are its leaves). Similarly, the maximum of node 13 and 15 is
taken to count and then added to node 7. Repeat the steps for every sub-tree till we reach
the node.
Let DPi be the maximum summation of node values in the path between i and any of its
leaves moving downwards. Traverse the tree using DFS traversal. Store the maximum
877
Chapter 143. Dynamic Programming on Trees | Set-1
of all the leaves of the sub-tree, and add it to the root of the sub-tree. At the end, DP1 will
have the maximum sum of the node values from root to any of the leaves without re-visiting
any node.
Below is the implementation of the above idea :
CPP
878
Chapter 143. Dynamic Programming on Trees | Set-1
return dp[1];
}
// Driver Code
int main()
{
// number of nodes
int n = 14;
// adjacency list
vector<int> v[n + 1];
// create undirected edges
// initialize the tree given in the diagram
v[1].push_back(2), v[2].push_back(1);
v[1].push_back(3), v[3].push_back(1);
v[1].push_back(4), v[4].push_back(1);
v[2].push_back(5), v[5].push_back(2);
v[2].push_back(6), v[6].push_back(2);
v[3].push_back(7), v[7].push_back(3);
v[4].push_back(8), v[8].push_back(4);
v[4].push_back(9), v[9].push_back(4);
v[4].push_back(10), v[10].push_back(4);
v[5].push_back(11), v[11].push_back(5);
v[5].push_back(12), v[12].push_back(5);
v[7].push_back(13), v[13].push_back(7);
v[7].push_back(14), v[14].push_back(7);
// values of node 1, 2, 3....14
int a[] = { 3, 2, 1, 10, 1, 3, 9, 1, 5, 3, 4, 5, 9, 8 };
// function call
cout << maximumValue(a, v);
return 0;
}
Output:
22
Source
https://www.geeksforgeeks.org/dynamic-programming-trees-set-1/
879
Chapter 144
How many different Unlabeled Binary Trees can be there with n nodes?
880
Chapter 144. Enumeration of Binary Trees
The idea is to consider all possible pair of counts for nodes in left and right subtrees and
multiply the counts for a particular pair. Finally add results of all pairs.
The above pattern basically represents n’th Catalan Numbers. First few catalan numbers
are 1 1 2 5 14 42 132 429 1430 4862,…
Here,
T(i-1) represents number of nodes on the left-sub-tree
T(n−i-1) represents number of nodes on the right-sub-tree
n’th Catalan Number can also be evaluated using direct formula.
Number of Binary Search Trees (BST) with n nodes is also same as number of unlabeled
trees. The reason for this is simple, in BST also we can make any key as root, If root is i’th
key in sorted order, then i-1 keys can go on one side and (n-i) keys can go on other side.
How many labeled Binary Trees can be there with n nodes?
To count labeled trees, we can use above count for unlabeled trees. The idea is simple,
every unlabeled tree with n nodes can create n! different labeled trees by assigning different
permutations of labels to all nodes.
Therefore,
Source
https://www.geeksforgeeks.org/enumeration-of-binary-trees/
881
Chapter 145
Output : 1 2 3 2 4 2 1
Input :
882
Chapter 145. Euler Tour of Tree
Output : 1 5 4 2 4 3 4 5 1
Euler tour is defined as a way of traversing tree such that each vertex is added to the tour
when we visit it (either moving down from parent vertex or returning from child vertex).
We start from root and reach back to root after visiting all vertices.
It requires exactly 2*N-1 vertices to store Euler tour.
Approach: We will run DFS(Depth first search) algorithm on Tree as:
883
Chapter 145. Euler Tour of Tree
884
Chapter 145. Euler Tour of Tree
int vis[MAX];
// Array to store Euler Tour
int Euler[2 * MAX];
// Function to add edges to tree
void add_edge(int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
// Function to store Euler Tour of tree
void eulerTree(int u, int &indx)
{
vis[u] = 1;
Euler[indx++] = u;
for (auto it : adj[u]) {
if (!vis[it]) {
eulerTree(it, indx);
Euler[indx++] = u;
}
}
}
// Function to print Euler Tour of tree
void printEulerTour(int root, int N)
{
int index = 0;
eulerTree(root, index);
for (int i = 0; i < (2*N-1); i++)
cout << Euler[i] << " ";
}
// Driver code
int main()
{
int N = 4;
add_edge(1, 2);
add_edge(2, 3);
add_edge(2, 4);
// Consider 1 as root and print
// Euler tour
printEulerTour(1, N);
return 0;
885
Chapter 145. Euler Tour of Tree
Output:
1 2 3 2 4 2 1
Source
https://www.geeksforgeeks.org/euler-tour-tree/
886
Chapter 146
887
Chapter 146. Euler Tour | Subtree Sum using Segment Tree
Queries :
1. Sum of all the subtrees of node 1.
2. Update the value of node 6 to 10.
3. Sum of all the subtrees of node 2.
Answers :
1. 6 + 5 + 4 + 3 + 2 + 1 = 21
2.
3. 10 + 5 + 2 = 17
Time Complexity Analysis :
Such queries can be performed using depth for search(dfs) in O(n) time complexity.
Efficient Approach :
The time complexity for such queries can be reduced to O(log(n)) time by converting the
rooted tree into segment tree using Euler tour technique. So, When the number of queries
are q, the total complexity becomes O(q*5log(n)).
Euler Tour :
In Euler tour Technique, each vertex is added to the vector twice, while descending into it
and while leaving it.
Let us understand with the help of previous example :
888
Chapter 146. Euler Tour | Subtree Sum using Segment Tree
On performing depth for search(DFS) using euler tour technique on the given rooted tree,
the vector so formed is :
s[]={1, 2, 6, 6, 5, 5, 2, 3, 4, 4, 3, 1}
889
Chapter 146. Euler Tour | Subtree Sum using Segment Tree
For the output and update query, store the entry time and exit time(which serve as index
range) for each node of the rooted tree.
s[]={1, 2, 6, 6, 5, 5, 2, 3, 4, 4, 3, 1}
Query of type 1 :
Find the range sum on segment tree for output query where range is exit time and entry
time of the rooted tree node. Deduce that the answer is always twice the expected answer
because each node is added twice in segment tree. So reduce the answer by half.
Query of type 2 :
For update query, update the leaf node of segment tree at the entry time and exit time of
the rooted tree node.
Below is the implementation of above approach :
890
Chapter 146. Euler Tour | Subtree Sum using Segment Tree
891
Chapter 146. Euler Tour | Subtree Sum using Segment Tree
}
/* A recursive function to update the
nodes which have the given index in
their range. The following are
parameters pos --> index of current
node in segment tree seg[]. idx -->
index of the element to be updated.
This index is in input array.
val --> Value to be change at node idx
*/
int update(int pos, int low, int high,
int idx, int val)
{
if (low == high) {
seg[pos] = val;
}
else {
int mid = (low + high) / 2;
if (low <= idx && idx <= mid) {
update(2 * pos, low, mid,
idx, val);
}
else {
update(2 * pos + 1, mid + 1,
high, idx, val);
}
seg[pos] = seg[2 * pos] + seg[2 * pos + 1];
}
}
/* A recursive function to form array
ar[] from a directed tree .
*/
int dfs(int root)
{
// pushing each node in vector s
s.push_back(root);
if (v[root].size() == 0)
return root;
for (int i = 0; i < v[root].size(); i++) {
int temp = dfs(v[root][i]);
s.push_back(temp);
}
return root;
892
Chapter 146. Euler Tour | Subtree Sum using Segment Tree
}
// Driver program to test above functions
int main()
{
// Edges between the nodes
v[1].push_back(2);
v[1].push_back(3);
v[2].push_back(6);
v[2].push_back(5);
v[3].push_back(4);
// Calling dfs function.
int temp = dfs(1);
s.push_back(temp);
// Storing entry time and exit
// time of each node
vector<pair<int, int> > p;
for (int i = 0; i <= vertices; i++)
p.push_back(make_pair(0, 0));
for (int i = 0; i < s.size(); i++) {
if (p[s[i]].first == 0)
p[s[i]].first = i + 1;
else
p[s[i]].second = i + 1;
}
// Build segment tree from array ar[].
segment(0, s.size() - 1, 1);
// query of type 1 return the
// sum of subtree at node 1.
int node = 1;
int e = p[node].first;
int f = p[node].second;
int ans = query(1, 1, s.size(), e, f);
// print the sum of subtree
cout << "Subtree sum of node " << node << " is : " << (ans / 2) << endl;
// query of type 2 return update
// the subtree at node 6.
int val = 10;
node = 6;
893
Chapter 146. Euler Tour | Subtree Sum using Segment Tree
e = p[node].first;
f = p[node].second;
update(1, 1, s.size(), e, val);
update(1, 1, s.size(), f, val);
// query of type 1 return the
// sum of subtree at node 2.
node = 2;
e = p[node].first;
f = p[node].second;
ans = query(1, 1, s.size(), e, f);
// print the sum of subtree
cout << "Subtree sum of node " << node << " is : " << (ans / 2) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/euler-tour-subtree-sum-using-segment-tree/
894
Chapter 147
Input :
Output: 1 5 4 2 4 3 4 5 1
Approach:
895
Chapter 147. Euler tour of Binary Tree
Euler tour of tree has been already discussed where it can be applied to N-ary tree which is
represented by adjacency list. If a Binary tree is represented by the classical structured way
by links and nodes, then there need to first convert the tree into adjacency list representation
and then we can find the Euler tour if we want to apply method discussed in the original post.
But this increases the space complexity of the program. Here, In this post, a generalized
space-optimized version is discussed which can be directly applied to binary trees represented
by structure nodes.
This method :
(1) Works without the use of Visited arrays.
(2) Requires exactly 2*N-1 vertices to store Euler tour.
896
Chapter 147. Euler tour of Binary Tree
897
Chapter 147. Euler tour of Binary Tree
Output:
1 2 4 2 5 2 1 3 6 8 6 3 7 3 1
Source
https://www.geeksforgeeks.org/euler-tour-binary-tree/
898
Chapter 148
Input :
Root node of the below tree
Output :
100
Input :
Root node of the below tree
Output :
110
As all the operators in the tree are binary hence each node will have either 0 or 2 children.
As it can be inferred from the examples above , the integer values would appear at the leaf
nodes , while the interior nodes represent the operators.
To evaluate the syntax tree , a recursive approach can be followed .
Algorithm :
Let t be the syntax tree
If t is not null then
899
Chapter 148. Evaluation of Expression Tree
The time complexity would be O(n), as each node is visited once. Below is a C++ program
for the same:
C/C++
900
Chapter 148. Evaluation of Expression Tree
// leaf node i.e, an integer
if (!root->left && !root->right)
return toInt(root->info);
// Evaluate left subtree
int l_val = eval(root->left);
// Evaluate right subtree
int r_val = eval(root->right);
// Check which operator to apply
if (root->info=="+")
return l_val+r_val;
if (root->info=="-")
return l_val-r_val;
if (root->info=="*")
return l_val*r_val;
return l_val/r_val;
}
//driver function to check the above program
int main()
{
// create a syntax tree
node *root = new node("+");
root->left = new node("*");
root->left->left = new node("5");
root->left->right = new node("4");
root->right = new node("-");
root->right->left = new node("100");
root->right->right = new node("20");
cout << eval(root) << endl;
delete(root);
root = new node("+");
root->left = new node("*");
root->left->left = new node("5");
root->left->right = new node("4");
root->right = new node("-");
root->right->left = new node("100");
root->right->right = new node("/");
root->right->right->left = new node("20");
root->right->right->right = new node("2");
901
Chapter 148. Evaluation of Expression Tree
cout << eval(root);
return 0;
}
Python
902
Chapter 148. Evaluation of Expression Tree
if __name__=='__main__':
# creating a sample tree
root = node('+')
root.left = node('*')
root.left.left = node('5')
root.left.right = node('4')
root.right = node('-')
root.right.left = node('100')
root.right.right = node('20')
print evaluateExpressionTree(root)
root = None
#creating a sample tree
root = node('+')
root.left = node('*')
root.left.left = node('5')
root.left.right = node('4')
root.right = node('-')
root.right.left = node('100')
root.right.right = node('/')
root.right.right.left = node('20')
root.right.right.right = node('2')
print evaluateExpressionTree(root)
# This code is contributed by Harshit Sidhwa
Output:
100
110
Source
https://www.geeksforgeeks.org/evaluation-of-expression-tree/
903
Chapter 149
Expression Tree
Inorder traversal of expression tree produces infix version of given postfix expression (same
with preorder traversal it gives prefix expression)
Evaluating the expression represented by expression tree:
904
Chapter 149. Expression Tree
C/C++
905
Chapter 149. Expression Tree
inorder(t->left);
printf("%c ", t->value);
inorder(t->right);
}
}
// A utility function to create a new node
et* newNode(int v)
{
et *temp = new et;
temp->left = temp->right = NULL;
temp->value = v;
return temp;
};
// Returns root of constructed tree for given
// postfix expression
et* constructTree(char postfix[])
{
stack<et *> st;
et *t, *t1, *t2;
// Traverse through every character of
// input expression
for (int i=0; i<strlen(postfix); i++)
{
// If operand, simply push into stack
if (!isOperator(postfix[i]))
{
t = newNode(postfix[i]);
st.push(t);
}
else // operator
{
t = newNode(postfix[i]);
// Pop two top nodes
t1 = st.top(); // Store top
st.pop(); // Remove top
t2 = st.top();
st.pop();
// make them children
t->right = t1;
t->left = t2;
// Add this subexpression to stack
st.push(t);
906
Chapter 149. Expression Tree
}
}
// only element will be root of expression
// tree
t = st.top();
st.pop();
return t;
}
// Driver program to test above
int main()
{
char postfix[] = "ab+ef*g*-";
et* r = constructTree(postfix);
printf("infix expression is \n");
inorder(r);
return 0;
}
Java
907
Chapter 149. Expression Tree
return true;
}
return false;
}
// Utility function to do inorder traversal
void inorder(Node t) {
if (t != null) {
inorder(t.left);
System.out.print(t.value + " ");
inorder(t.right);
}
}
// Returns root of constructed tree for given
// postfix expression
Node constructTree(char postfix[]) {
Stack<Node> st = new Stack();
Node t, t1, t2;
// Traverse through every character of
// input expression
for (int i = 0; i < postfix.length; i++) {
// If operand, simply push into stack
if (!isOperator(postfix[i])) {
t = new Node(postfix[i]);
st.push(t);
} else // operator
{
t = new Node(postfix[i]);
// Pop two top nodes
// Store top
t1 = st.pop(); // Remove top
t2 = st.pop();
// make them children
t.right = t1;
t.left = t2;
// System.out.println(t1 + "" + t2);
// Add this subexpression to stack
st.push(t);
}
}
// only element will be root of expression
908
Chapter 149. Expression Tree
// tree
t = st.peek();
st.pop();
return t;
}
public static void main(String args[]) {
ExpressionTree et = new ExpressionTree();
String postfix = "ab+ef*g*-";
char[] charArray = postfix.toCharArray();
Node root = et.constructTree(charArray);
System.out.println("infix expression is");
et.inorder(root);
}
}
// This code has been contributed by Mayank Jaiswal
Python
909
Chapter 149. Expression Tree
inorder(t.right)
# Returns root of constructed tree for
# given postfix expression
def constructTree(postfix):
stack = []
# Traverse through every character of input expression
for char in postfix :
# if operand, simply push into stack
if not isOperator(char):
t = Et(char)
stack.append(t)
# Operator
else:
# Pop two top nodes
t = Et(char)
t1 = stack.pop()
t2 = stack.pop()
# make them children
t.right = t1
t.left = t2
# Add this subexpression to stack
stack.append(t)
# Only element will be the root of expression tree
t = stack.pop()
return t
# Driver program to test above
postfix = "ab+ef*g*-"
r = constructTree(postfix)
print "Infix expression is"
inorder(r)
Output:
infix expression is
a + b - e * f * g
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
910
Chapter 149. Expression Tree
Source
https://www.geeksforgeeks.org/expression-tree/
911
Chapter 150
Output:
Doubly Linked List
785910
Modified Tree:
1
/ \
2 3
/ \
4 6
We need to traverse all leaves and connect them by changing their left and right pointers.
912
Chapter 150. Extract Leaves of a Binary Tree in a Doubly Linked List
We also need to remove them from Binary Tree by changing left or right pointers in parent
nodes. There can be many ways to solve this. In the following implementation, we add
leaves at the beginning of current linked list and update head of the list using pointer to
head pointer. Since we insert at the beginning, we need to process leaves in reverse order.
For reverse order, we first traverse the right subtree then the left subtree. We use return
values to update left or right pointers in parent nodes.
C
913
Chapter 150. Extract Leaves of a Binary Tree in a Doubly Linked List
914
Chapter 150. Extract Leaves of a Binary Tree in a Doubly Linked List
root->right->right->right = newNode(10);
printf("Inorder Trvaersal of given Tree is:\n");
print(root);
root = extractLeafList(root, &head);
printf("\nExtracted Double Linked list is:\n");
printList(head);
printf("\nInorder traversal of modified tree is:\n");
print(root);
return 0;
}
Java
915
Chapter 150. Extract Leaves of a Binary Tree in a Doubly Linked List
head = root;
prev = root;
}
else
{
prev.right = root;
root.left = prev;
prev = root;
}
return null;
}
root.left = extractLeafList(root.left);
root.right = extractLeafList(root.right);
return root;
}
//Prints the DLL in both forward and reverse directions.
public void printDLL(Node head)
{
Node last = null;
while (head != null)
{
System.out.print(head.data + " ");
last = head;
head = head.right;
}
}
void inorder(Node node)
{
if (node == null)
return;
inorder(node.left);
System.out.print(node.data + " ");
inorder(node.right);
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.right = new Node(6);
916
Chapter 150. Extract Leaves of a Binary Tree in a Doubly Linked List
Python
917
Chapter 150. Extract Leaves of a Binary Tree in a Doubly Linked List
918
Chapter 150. Extract Leaves of a Binary Tree in a Doubly Linked List
root = extractLeafList(root)
print "\nExtract Double Linked List is:"
printList(extractLeafList.head)
print "\nInorder traversal of modified tree is:"
printInorder(root)
Output:
Time Complexity: O(n), the solution does a single traversal of given Binary Tree.
This article is contributed by Chandra Prakash. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/connect-leaves-doubly-linked-list/
919
Chapter 151
Input : v = 48
Output : Root of below tree
48
/\
2 24
/\
2 12
/\
2 6
/\
2 3
920
Chapter 151. Factor Tree of a given Number
// a given number
#include<bits/stdc++.h>
using namespace std;
// Tree node
struct Node
{
struct Node *left, *right;
int key;
};
// Utility function to create a new tree Node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
// Constructs factor tree for given value and stores
// root of tree at given reference.
void createFactorTree(struct Node **node_ref, int v)
{
(*node_ref) = newNode(v);
// the number is factorized
for (int i = 2 ; i < v/2 ; i++)
{
if (v % i != 0)
continue;
// If we found a factor, we construct left
// and right subtrees and return. Since we
// traverse factors starting from smaller
// to greater, left child will always have
// smaller factor
createFactorTree(&((*node_ref)->left), i);
createFactorTree(&((*node_ref)->right), v/i);
return;
}
}
// Iterative method to find height of Bianry Tree
void printLevelOrder(Node *root)
{
// Base Case
if (root == NULL) return;
921
Chapter 151. Factor Tree of a given Number
queue<Node *> q;
q.push(root);
while (q.empty() == false)
{
// Print front of queue and remove
// it from queue
Node *node = q.front();
cout << node->key << " ";
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
}
}
// driver program
int main()
{
int val = 48;// sample value
struct Node *root = NULL;
createFactorTree(&root, val);
cout << "Level order traversal of "
"constructed factor tree";
printLevelOrder(root);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/factor-tree-of-a-given-number/
922
Chapter 152
Input :
1
/ \
2 3
/ / \
4 2 4
/
4
Output :
2
/ and 4
4
Explanation: Above Trees are two duplicate subtrees.
Therefore, you need to return above trees root in the
form of a list.
The idea is to use hashing. We store inorder traversals of subtrees in a hash. Since simple
inorder traversal cannot uniquely identify a tree, we use symbols like ‘(‘ and ‘)’ to represent
NULL nodes.
We pass a Unordered Map in C++ as an argument to the helper function which recursively
calculates inorder string and increases its count in map. If any string gets repeated, then it
will imply duplication of the subtree rooted at that node so push that node in Final result
and return the vector of these nodes.
923
Chapter 152. Find All Duplicate Subtrees
C++
924
Chapter 152. Find All Duplicate Subtrees
Java
925
Chapter 152. Find All Duplicate Subtrees
Output:
926
Chapter 152. Find All Duplicate Subtrees
4 2
Source
https://www.geeksforgeeks.org/find-duplicate-subtrees/
927
Chapter 153
We strongly recommend you to minimize your browser and try this yourself
first.
928
Chapter 153. Find Count of Single Valued Subtrees
A Simple Solution is to traverse the tree. For every traversed node, check if all values
under this node are same or not. If same, then increment count. Time complexity of this
solution is O(n2 ).
An Efficient Solution is to traverse the tree in bottom up manner. For every subtree
visited, return true if subtree rooted under it is single valued and increment count. So the
idea is to use count as a reference parameter in recursive calls and use returned values to
find out if left and right subtrees are single valued or not.
Below is the implementation of above idea.
C++
929
Chapter 153. Find Count of Single Valued Subtrees
930
Chapter 153. Find Count of Single Valued Subtrees
Java
931
Chapter 153. Find Count of Single Valued Subtrees
932
Chapter 153. Find Count of Single Valued Subtrees
Python
933
Chapter 153. Find Count of Single Valued Subtrees
Output:
Time complexity of this solution is O(n) where n is number of nodes in given binary tree.
Thanks to Gaurav Ahirwar for suggesting above solution.
934
Chapter 153. Find Count of Single Valued Subtrees
Source
https://www.geeksforgeeks.org/find-count-of-singly-subtrees/
935
Chapter 154
Input: parent[] = {1 5 5 2 2 -1 3}
Output: 4
The given array represents following Binary Tree
5
/ \
1 2
/ / \
0 3 4
/
6
936
Chapter 154. Find Height of Binary Tree represented by Parent array
5
/
6
937
Chapter 154. Find Height of Binary Tree represented by Parent array
Java
938
Chapter 154. Find Height of Binary Tree represented by Parent array
939
Chapter 154. Find Height of Binary Tree represented by Parent array
return ht;
}
// Driver program to test above functions
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
// int parent[] = {1, 5, 5, 2, 2, -1, 3};
int parent[] = new int[]{-1, 0, 0, 1, 1, 3, 5};
int n = parent.length;
System.out.println("Height is " + tree.findHeight(parent, n));
}
}
Python
940
Chapter 154. Find Height of Binary Tree represented by Parent array
Output:
Height is 5
Note that the time complexity of this programs seems more than O(n). If we take a closer
look, we can observe that depth of every node is evaluated only once.
This article is contributed by Siddharth. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/find-height-binary-tree-represented-parent-array/
941
Chapter 155
942
Chapter 155. Find LCA in Binary Tree using RMQ
There can be many approaches to solve the LCA problem. The approaches differ in their
time and space complexities. Here is a link to a couple of them (these do not involve
reduction to RMQ).
Range Minimum Query (RMQ) is used on arrays to find the position of an element
with the minimum value between two specified indices. Different approaches for solving
RMQ have been discussed here and here. In this article, Segment Tree based approach is
discussed. With segment tree, preprocessing time is O(n) and time to for range minimum
query is O(Logn). The extra space required is O(n) to store the segment tree.
Reduction of LCA to RMQ:
The idea is to traverse the tree starting from root by an Euler tour (traversal without lifting
pencil), which is a DFS-type traversal with preorder traversal characteristics.
Observation: The LCA of nodes 4 and 9 is node 2, which happens to be the node closest
to the root amongst all those encountered between the visits of 4 and 9 during a DFS of
T. This observation is the key to the reduction. Let’s rephrase: Our node is the node at
the smallest level and the only node at that level amongst all the nodes that occur between
consecutive occurrences (any) of u and v in the Euler tour of T.
We require three arrays for implementation:
943
Chapter 155. Find LCA in Binary Tree using RMQ
3. Index of the first occurrence of a node in Euler tour of T (since any occurrence would
be good, let’s track the first one)
Algorithm:
1. Do a Euler tour on the tree, and fill the euler, level and first occurrence arrays.
2. Using the first occurrence array, get the indices corresponding to the two nodes which
will be the corners of the range in the level array that is fed to the RMQ algorithm
for the minimum value.
3. Once the algorithm return the index of the minimum level in the range, we use it to
determine the LCA using Euler tour array.
944
Chapter 155. Find LCA in Binary Tree using RMQ
// log base 2 of x
int Log2(int x)
{
int ans = 0 ;
while (x>>=1) ans++;
return ans ;
}
/* A recursive function to get the minimum value in a given range
of array indexes. The following are parameters for this function.
st --> Pointer to segment tree
index --> Index of current node in the segment tree. Initially
0 is passed as root is always at index 0
ss & se --> Starting and ending indexes of the segment represented
by current node, i.e., st[index]
qs & qe --> Starting and ending indexes of query range */
int RMQUtil(int index, int ss, int se, int qs, int qe, int *st)
{
// If segment of this node is a part of given range, then return
// the min of the segment
if (qs <= ss && qe >= se)
return st[index];
// If segment of this node is outside the given range
else if (se < qs || ss > qe)
return -1;
// If a part of this segment overlaps with the given range
int mid = (ss + se)/2;
int q1 = RMQUtil(2*index+1, ss, mid, qs, qe, st);
int q2 = RMQUtil(2*index+2, mid+1, se, qs, qe, st);
if (q1==-1) return q2;
else if (q2==-1) return q1;
return (level[q1] < level[q2]) ? q1 : q2;
}
// Return minimum of elements in range from index qs (quey start) to
// qe (query end). It mainly uses RMQUtil()
int RMQ(int *st, int n, int qs, int qe)
{
// Check for erroneous input values
if (qs < 0 || qe > n-1 || qs > qe)
{
945
Chapter 155. Find LCA in Binary Tree using RMQ
printf("Invalid Input");
return -1;
}
return RMQUtil(0, 0, n-1, qs, qe, st);
}
// A recursive function that constructs Segment Tree for array[ss..se].
// si is index of current node in segment tree st
void constructSTUtil(int si, int ss, int se, int arr[], int *st)
{
// If there is one element in array, store it in current node of
// segment tree and return
if (ss == se)st[si] = ss;
else
{
// If there are more than one elements, then recur for left and
// right subtrees and store the minimum of two values in this node
int mid = (ss + se)/2;
constructSTUtil(si*2+1, ss, mid, arr, st);
constructSTUtil(si*2+2, mid+1, se, arr, st);
if (arr[st[2*si+1]] < arr[st[2*si+2]])
st[si] = st[2*si+1];
else
st[si] = st[2*si+2];
}
}
/* Function to construct segment tree from given array. This function
allocates memory for segment tree and calls constructSTUtil() to
fill the allocated memory */
int *constructST(int arr[], int n)
{
// Allocate memory for segment tree
// Height of segment tree
int x = Log2(n)+1;
// Maximum size of segment tree
int max_size = 2*(1<<x) - 1; // 2*pow(2,x) -1
int *st = new int[max_size];
// Fill the allocated memory st
constructSTUtil(0, 0, n-1, arr, st);
946
Chapter 155. Find LCA in Binary Tree using RMQ
947
Chapter 155. Find LCA in Binary Tree using RMQ
/* To start filling euler and level arrays from index 0 */
ind = 0;
/* Start Euler tour with root node on level 0 */
eulerTour(root, 0);
/* construct segment tree on level array */
int *st = constructST(level, 2*V-1);
/* If v before u in Euler tour. For RMQ to work, first
parameter 'u' must be smaller than second 'v' */
if (firstOccurrence[u]>firstOccurrence[v])
std::swap(u, v);
// Starting and ending indexes of query range
int qs = firstOccurrence[u];
int qe = firstOccurrence[v];
// query for index of LCA in tour
int index = RMQ(st, 2*V-1, qs, qe);
/* return LCA node */
return euler[index];
}
// Driver program to test above functions
int main()
{
// Let us create the Binary Tree as shown in the diagram.
Node * root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->right->left = newNode(8);
root->left->right->right = newNode(9);
int u = 4, v = 9;
printf("The LCA of node %d and node %d is node %d.\n",
u, v, findLCA(root, u, v));
return 0;
}
Java
948
Chapter 155. Find LCA in Binary Tree using RMQ
949
Chapter 155. Find LCA in Binary Tree using RMQ
950
Chapter 155. Find LCA in Binary Tree using RMQ
951
Chapter 155. Find LCA in Binary Tree using RMQ
952
Chapter 155. Find LCA in Binary Tree using RMQ
/* If v before u in Euler tour. For RMQ to work, first
parameter 'u' must be smaller than second 'v' */
if (f_occur[u] > f_occur[v])
u = swap(u, u = v);
// Starting and ending indexes of query range
int qs = f_occur[u];
int qe = f_occur[v];
// query for index of LCA in tour
int index = RMQ(sc, 2 * v - 1, qs, qe);
/* return LCA node */
return euler[index];
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
// Let us create the Binary Tree as shown in the diagram.
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.left.right.left = new Node(8);
tree.root.left.right.right = new Node(9);
int u = 4, v = 9;
System.out.println("The LCA of node " + u + " and " + v + " is "
+ tree.findLCA(tree.root, u, v));
}
}
// This code has been contributed by Mayank Jaiswal
Output:
Note:
953
Chapter 155. Find LCA in Binary Tree using RMQ
Time complexity:
1. Euler tour: Number of nodes is V. For a tree, E = V-1. Euler tour (DFS) will take
O(V+E) which is O(2*V) which can be written as O(V).
2. Segment Tree construction : O(n) where n = V + E = 2*V – 1.
3. Range Minimum query: O(log(n))
Overall this method takes O(n) time for preprocssing, but takes O(Log n) time for query.
Therefore, it can be useful when we have a single tree on which we want to perform large
number of LCA queries (Note that LCA is useful for finding shortest path between two
nodes of Binary Tree)
Auxiliary Space:
Overall: O(n)
Another observation is that the adjacent elements in level array differ by 1. This can be
used to convert a RMQ problem to a LCA problem.
This article is contributed by Yash Varyani. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/find-lca-in-binary-tree-using-rmq/
954
Chapter 156
Note that the path must end on a leaf node. For example, minimum height of below Binary
Tree is also 2.
10
/
5
The idea is to traverse the given Binary Tree. For every node, check if it is a leaf node. If
yes, then return 1. If not leaf node then if left subtree is NULL, then recur for right subtree.
And if right subtree is NULL, then recur for left subtree. If both left and right subtrees are
not NULL, then take the minimum of two heights.
955
Chapter 156. Find Minimum Depth of a Binary Tree
C++
956
Chapter 156. Find Minimum Depth of a Binary Tree
{
// Let us construct the Tree shown in the above figure
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << minDepth(root);
return 0;
}
Java
957
Chapter 156. Find Minimum Depth of a Binary Tree
return 1;
// If left subtree is NULL, recur for right subtree
if (root.left == null)
return minimumDepth(root.right) + 1;
// If right subtree is NULL, recur for left subtree
if (root.right == null)
return minimumDepth(root.left) + 1;
return Math.min(minimumDepth(root.left),
minimumDepth(root.right)) + 1;
}
/* Driver program to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("The minimum depth of "+
"binary tree is : " + tree.minimumDepth());
}
}
Python
958
Chapter 156. Find Minimum Depth of a Binary Tree
return 1
# If left subtree is Null, recur for right subtree
if root.left is None:
return minDepth(root.right)+1
# If right subtree is Null , recur for left subtree
if root.right is None:
return minDepth(root.left) +1
return min(minDepth(root.left), minDepth(root.right))+1
# Driver Program
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print minDepth(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time complexity of above solution is O(n) as it traverses the tree only once.
Thanks to Gaurav Ahirwar for providing above solution.
The above method may end up with complete traversal of Binary Tree even when the
topmost leaf is close to root. A Better Solution is to do Level Order Traversal. While
doing traversal, returns depth of the first encountered leaf node. Below is implementation
of this solution.
959
Chapter 156. Find Minimum Depth of a Binary Tree
960
Chapter 156. Find Minimum Depth of a Binary Tree
qi.node = node->right;
qi.depth = depth+1;
q.push(qi);
}
}
return 0;
}
// Utility function to create a new tree Node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in above diagram
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << minDepth(root);
return 0;
}
Python
961
Chapter 156. Find Minimum Depth of a Binary Tree
Output:
Thanks to Manish Chauhan for suggesting above idea and Ravi for providing implementa-
tion.
Improved By : mrunalupadhyay
962
Chapter 156. Find Minimum Depth of a Binary Tree
Source
https://www.geeksforgeeks.org/find-minimum-depth-of-a-binary-tree/
963
Chapter 157
3rd time we can move 3 steps either way from -3, 1, -1, 3
-3: -6(-3-3) 0(-3+3)
1: -2(1-3) 4(1+3)
-1: -4(-1-3) 2(-1+3)
3: 0(0-3) 6(3+3)
Examples:
Input : n = 10
Output : 4
We can reach 10 in 4 steps, 1, 3, 6, 10
Input : n = 13
964
Chapter 157. Find a number in minimum steps
Output : 5
We can reach 10 in 4 steps, -1, 2, 5, 9, 14
This problem can be modeled as tree. We put initial point 0 at root, 1 and -1 as children of
root. Next level contains values at distance 2 and so on.
0
/ \
-1 1
/ \ / \
1 -3 -1 3
/ \ / \ / \ / \
The problem is now to find the closes node to root with value n. The idea is to do Level
Order Traversal of tree to find the closest node. Note that using DFS for closest node is
never a good idea (we may end up going down many unnecessary levels).
Below is C++ implementation of above idea.
965
Chapter 157. Find a number in minimum steps
q.pop();
// To avoid infinite loop
if (temp.no >= InF || temp.no <= -InF)
break;
// Check if dequeued number is same as n
if (temp.no == n)
{
cout << "Found number n at level "
<< temp.level-1;
break;
}
// Insert children of dequeued node to queue
q.push(number(temp.no+temp.level, temp.level+1));
q.push(number(temp.no-temp.level, temp.level+1));
}
}
// Driver code
int main()
{
findnthnumber(13);
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/find-a-number-in-minimum-steps/
966
Chapter 158
Find all possible binary trees with given Inorder Traversal - GeeksforGeeks
Given an array that represents Inorder Traversal, find all possible Binary Trees with the
given Inorder traversal and print their preorder traversals.
Examples:
967
Chapter 158. Find all possible binary trees with given Inorder Traversal
We strongly recommend you to minimize your browser and try this yourself
first.
Let given inorder traversal be in[]. In the given traversal, all nodes in left subtree of in[i]
must appear before it and in right subtree must appear after it. So when we consider in[i]
as root, all elements from in[0] to in[i-1] will be in left subtree and in[i+1] to n-1 will be
in right subtree. If in[0] to in[i-1] can form x different trees and in[i+1] to in[n-1] can from
y different trees then we will have x*y total trees when in[i] as root. So we simply iterate
from 0 to n-1 for root. For every node in[i], recursively find different left and right subtrees.
If we take a closer look, we can notice that the count is basically n’th Catalan number. We
have discussed different approaches to find n’th Catalan number here.
The idea is to maintain a list of roots of all Binary Trees. Recursively construct all possible
left and right subtrees. Create a tree for every pair of left and right subtree and add the
tree to list. Below is detailed algorithm.
C++
968
Chapter 158. Find all possible binary trees with given Inorder Traversal
969
Chapter 158. Find all possible binary trees with given Inorder Traversal
Java
970
Chapter 158. Find all possible binary trees with given Inorder Traversal
data = item;
left = null;
right = null;
}
}
/* Class to print Level Order Traversal */
class BinaryTree {
Node root;
// A utility function to do preorder traversal of BST
void preOrder(Node node) {
if (node != null) {
System.out.print(node.data + " " );
preOrder(node.left);
preOrder(node.right);
}
}
// Function for constructing all possible trees with
// given inorder traversal stored in an array from
// arr[start] to arr[end]. This function returns a
// vector of trees.
Vector<Node> getTrees(int arr[], int start, int end) {
// List to store all possible trees
Vector<Node> trees= new Vector<Node>();
/* if start > end then subtree will be empty so
returning NULL in the list */
if (start > end) {
trees.add(null);
return trees;
}
/* Iterating through all values from start to end
for constructing left and right subtree
recursively */
for (int i = start; i <= end; i++) {
/* Constructing left subtree */
Vector<Node> ltrees = getTrees(arr, start, i - 1);
/* Constructing right subtree */
Vector<Node> rtrees = getTrees(arr, i + 1, end);
/* Now looping through all left and right subtrees
and connecting them to ith root below */
971
Chapter 158. Find all possible binary trees with given Inorder Traversal
Python
972
Chapter 158. Find all possible binary trees with given Inorder Traversal
973
Chapter 158. Find all possible binary trees with given Inorder Traversal
# Adding this tree to list
trees.append(node)
return trees
# Driver program to test above function
inp = [4 , 5, 7]
n = len(inp)
trees = getTrees(inp , 0 , n-1)
print "Preorder traversals of different possible\
Binary Trees are "
for i in trees :
preorder(i);
print ""
# This program is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Source
https://www.geeksforgeeks.org/find-all-possible-trees-with-given-inorder-traversal/
974
Chapter 159
1
/ \
2 3
/ / \
4 5 6
\ \
7 8
/ \
9 10
/
11
The idea is to recursively traverse the given binary tree and while traversing, maintain a
variable “level” which will store the current node’s level in the tree. If current node is leaf
then check “level” is odd or not. If level is odd then return it. If current node is not leaf,
then recursively find maximum depth in left and right subtrees, and return maximum of the
two depths.
C
975
Chapter 159. Find depth of the deepest odd level leaf node
976
Chapter 159. Find depth of the deepest odd level leaf node
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->right = newNode(7);
root->right->right->right = newNode(8);
root->right->left->right->left = newNode(9);
root->right->right->right->right = newNode(10);
root->right->right->right->right->left = newNode(11);
printf("%d is the required depth\n", depthOfOddLeaf(root));
getchar();
return 0;
}
Java
977
Chapter 159. Find depth of the deepest odd level leaf node
Python
978
Chapter 159. Find depth of the deepest odd level leaf node
self.data = data
self.left = None
self.right = None
# A recursive function to find depth of the deepest
# odd level leaf node
def depthOfOddLeafUtil(root, level):
# Base Case
if root is None:
return 0
# If this node is leaf and its level is odd, return
# its level
if root.left is None and root.right is None and level&1:
return level
# If not leaf, return the maximum value from left
# and right subtrees
return (max(depthOfOddLeafUtil(root.left, level+1),
depthOfOddLeafUtil(root.right, level+1)))
# Main function which calculates the depth of deepest odd
# level leaf .
# This function mainly uses depthOfOddLeafUtil()
def depthOfOddLeaf(root):
level = 1
depth = 0
return depthOfOddLeafUtil(root, level)
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.left = Node(5)
root.right.right = Node(6)
root.right.left.right = Node(7)
root.right.right.right = Node(8)
root.right.left.right.left = Node(9)
root.right.right.right.right = Node(10)
root.right.right.right.right.left= Node(11)
print "%d is the required depth" %(depthOfOddLeaf(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
979
Chapter 159. Find depth of the deepest odd level leaf node
Time Complexity: The function does a simple traversal of the tree, so the complexity is
O(n).
Iterative Approach
This approach is contributed by Mandeep Singh. Traverse the tree in iterative fashion for
each level, and whenever you encounter the leaf node, check if level is odd, if level is odd,
then update the result.
980
Chapter 159. Find depth of the deepest odd level leaf node
int level = 0;
// traverse until the
// queue is empty
while (!q.empty())
{
int size = q.size();
level += 1;
// traverse for
// complete level
while(size > 0)
{
Node* temp = q.front();
q.pop();
// check if the node is
// leaf node and level
// is odd if level is
// odd, then update result
if(!temp->left && !temp->right
&& (level % 2 != 0))
{
result = level;
}
// check for left child
if (temp->left)
{
q.push(temp->left);
}
// check for right child
if (temp->right)
{
q.push(temp->right);
}
size -= 1;
}
}
return result;
}
// driver program
int main()
{
// construct a tree
981
Chapter 159. Find depth of the deepest odd level leaf node
Output:
Source
https://www.geeksforgeeks.org/find-depth-of-the-deepest-odd-level-node/
982
Chapter 160
The distance between two nodes can be obtained in terms of lowest common ancestor. Fol-
lowing is the formula.
983
Chapter 160. Find distance between two nodes of a Binary Tree
984
Chapter 160. Find distance between two nodes of a Binary Tree
985
Chapter 160. Find distance between two nodes of a Binary Tree
986
Chapter 160. Find distance between two nodes of a Binary Tree
Java
987
Chapter 160. Find distance between two nodes of a Binary Tree
// It also sets d1, d2 and dist if one key is not ancestor of other
// d1 --> To store distance of n1 from root
// d2 --> To store distance of n2 from root
// lvl --> Level (or distance from root) of current node
// dist --> To store distance between n1 and n2
static Node findDistUtil(Node root, int n1, int n2, int lvl){
// Base case
if (root == null)
return null;
// If either n1 or n2 matches with root's key, report
// the presence by returning root (Note that if a key is
// ancestor of other, then the ancestor key becomes LCA
if (root.key == n1){
d1 = lvl;
return root;
}
if (root.key == n2)
{
d2 = lvl;
return root;
}
// Look for n1 and n2 in left and right subtrees
Node left_lca = findDistUtil(root.left, n1, n2, lvl + 1);
Node right_lca = findDistUtil(root.right, n1, n2, lvl + 1);
// If both of the above calls return Non-NULL, then one key
// is present in once subtree and other is present in other,
// So this node is the LCA
if (left_lca != null && right_lca != null)
{
dist = (d1 + d2) - 2*lvl;
return root;
}
// Otherwise check if left subtree or right subtree is LCA
return (left_lca != null)? left_lca : right_lca;
}
// The main function that returns distance between n1 and n2
// This function returns -1 if either n1 or n2 is not present in
// Binary Tree.
static int findDistance(Node root, int n1, int n2){
d1 = -1;
d2 = -1;
dist = 0;
988
Chapter 160. Find distance between two nodes of a Binary Tree
989
Chapter 160. Find distance between two nodes of a Binary Tree
Python
990
Chapter 160. Find distance between two nodes of a Binary Tree
Output:
Dist(4, 5) = 2
Dist(4, 6) = 4
Dist(3, 4) = 3
Dist(2, 4) = 1
Dist(8, 5) = 5
991
Chapter 160. Find distance between two nodes of a Binary Tree
Time Complexity: Time complexity of the above solution is O(n) as the method does a
single tree traversal.
Thanks to Atul Singh for providing the initial solution for this post.
Better Solution :
We first find LCA of two nodes. Then we find distance from LCA to two nodes.
C++
992
Chapter 160. Find distance between two nodes of a Binary Tree
// Returns level of key k if it is present in
// tree, otherwise returns -1
int findLevel(Node *root, int k, int level)
{
if(root == NULL) return -1;
if(root->key == k) return level;
int left = findLevel(root->left, k, level+1);
if (left == -1)
return findLevel(root->right, k, level+1);
return left;
}
int findDistance(Node* root, int a, int b)
{
// Your code here
Node* lca = LCA(root, a , b);
int d1 = findLevel(lca, a, 0);
int d2 = findLevel(lca, b, 0);
return d1 + d2;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree given in
// the above example
Node * root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
cout << "Dist(4, 5) = " << findDistance(root, 4, 5);
cout << "\nDist(4, 6) = " << findDistance(root, 4, 6);
cout << "\nDist(3, 4) = " << findDistance(root, 3, 4);
cout << "\nDist(2, 4) = " << findDistance(root, 2, 4);
cout << "\nDist(8, 5) = " << findDistance(root, 8, 5);
return 0;
}
Java
993
Chapter 160. Find distance between two nodes of a Binary Tree
994
Chapter 160. Find distance between two nodes of a Binary Tree
Python3
"""
A python program to find distance between n1
and n2 in binary tree
"""
# binary tree node
995
Chapter 160. Find distance between two nodes of a Binary Tree
class Node:
# Constructor to create new node
def __init__(self, data):
self.data = data
self.left = self.right = None
# This function returns pointer to LCA of
# two given values n1 and n2.
def LCA(root, n1, n2):
# Base case
if root is None:
return None
# If either n1 or n2 matches with root's
# key, report the presence by returning
# root
if root.data == n1 or root.data == n2:
return root
# Look for keys in left and right subtrees
left = LCA(root.left, n1, n2)
right = LCA(root.right, n1, n2)
if left is not None and right is not None:
return root
# Otherwise check if left subtree or
# right subtree is LCA
if left:
return left
else:
return right
# function to find distance of any node
# from root
def findLevel(root, data, d, level):
# Base case when tree is empty
if root is None:
return
# Node is found then append level
# value to list and return
if root.data == data:
d.append(level)
996
Chapter 160. Find distance between two nodes of a Binary Tree
return
findLevel(root.left, data, d, level + 1)
findLevel(root.right, data, d, level + 1)
# function to find distance between two
# nodes in a binary tree
def findDistance(root, n1, n2):
lca = LCA(root, n1, n2)
# to store distance of n1 from lca
d1 = []
# to store distance of n2 from lca
d2 = []
# if lca exist
if lca:
# distance of n1 from lca
findLevel(lca, n1, d1, 0)
# distance of n2 from lca
findLevel(lca, n2, d2, 0)
return d1[0] + d2[0]
else:
return -1
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right = Node(8)
print("Dist(4,5) = ", findDistance(root, 4, 5))
print("Dist(4,6) = ", findDistance(root, 4, 6))
print("Dist(3,4) = ", findDistance(root, 3, 4))
print("Dist(2,4) = ", findDistance(root, 2, 4))
print("Dist(8,5) = ", findDistance(root, 8, 5))
# This article is contributed by Shweta Singh.
997
Chapter 160. Find distance between two nodes of a Binary Tree
Output :
Dist(4, 5) = 2
Dist(4, 6) = 4
Dist(3, 4) = 3
Dist(2, 4) = 1
Dist(8, 5) = 5
Source
https://www.geeksforgeeks.org/find-distance-between-two-nodes-of-a-binary-tree/
998
Chapter 161
Input : x = 45,
Root of below tree
5
/ \
10 15
/ \ / \
20 25 30 35
\
45
Output : Distance = 3
There are three edges on path
from root to 45.
The idea is to traverse the tree from root. Check if x is present at root or in left subtree or
in right subtree. We initialize distance as -1 and add 1 to distance for all three cases.
999
Chapter 161. Find distance from root to given node in a binary tree
1000
Chapter 161. Find distance from root to given node in a binary tree
root->left->left = newNode(20);
root->left->right = newNode(25);
root->left->right->right = newNode(45);
root->right->left = newNode(30);
root->right->right = newNode(35);
cout << findDistance(root, 45);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-distance-root-given-node-binary-tree/
1001
Chapter 162
Second Tree
6
/ \
10 15
Output : 11 15
If we consider leaves of two trees in order,
we can see that 11 and 15 are the first leaves
that do not match.
Method 1 (Simple) :
Do Inorder traversal of both trees one by one, store the leaves of both trees in two different
lists. Finally find first values which are different in both lists. Time complexity is O(n1 +
n2) where n1 and n2 are number of nodes in two trees. Auxiliary space requirement is O(n1
+ n2).
1002
Chapter 162. Find first non matching leaves in two binary trees
Method 2 (Efficient)
This solution auxiliary space requirement as O(h1 + h2) where h1 and h2 are heights of
trees. We do Iterative Preorder traversal of both the trees simultaneously using stacks. We
maintain a stack for each tree. For every tree, keep pushing nodes in the stack till the top
node is a leaf node. Compare the two top nodes f both the stack. If they are equal, do
further traversal else return.
1003
Chapter 162. Find first non matching leaves in two binary trees
1004
Chapter 162. Find first non matching leaves in two binary trees
Output:
11 15
References:
• https://www.geeksforgeeks.org/amazon-interview-experience-set-337-sde-1/
• https://www.careercup.com/question?id=5673248478986240
Source
https://www.geeksforgeeks.org/find-first-non-matching-leaves-two-binary-trees/
1005
Chapter 163
Find height of a special binary tree whose leaf nodes are connected - GeeksforGeeks
Given a special binary tree whose leaf nodes are connected to form a circular doubly linked
list, find its height.
For example,
1
/ \
2 3
/ \
4 5
/
6
In the above binary tree, 6, 5 and 3 are leaf nodes and they form a circular doubly linked
list. Here, the left pointer of leaf node will act as a previous pointer of circular doubly linked
list and its right pointer will act as next pointer of circular doubly linked list.
The idea is to follow similar approach as we do for finding height of a normal binary tree.
We recursively calculate height of left and right subtrees of a node and assign height to the
node as max of the heights of two children plus 1. But left and right child of a leaf node are
null for normal binary trees. But, here leaf node is a circular doubly linked list node. So
for a node to be a leaf node, we check if node’s left’s right is pointing to the node and its
right’s left is also pointing to the node itself.
Below is C++ implementation of above idea –
1006
Chapter 163. Find height of a special binary tree whose leaf nodes are connected
1007
Chapter 163. Find height of a special binary tree whose leaf nodes are connected
}
// Driver code
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->left->left = newNode(6);
// Given tree contains 3 leaf nodes
Node *L1 = root->left->left->left;
Node *L2 = root->left->right;
Node *L3 = root->right;
// create circular doubly linked list out of
// leaf nodes of the tree
// set next pointer of linked list
L1->right = L2, L2->right = L3, L3->right = L1;
// set prev pointer of linked list
L3->left = L2, L2->left = L1, L1->left = L3;
// calculate height of the tree
cout << "Height of tree is " << maxDepth(root);
return 0;
}
Output:
Height of tree is 4
Source
https://www.geeksforgeeks.org/find-height-of-a-special-binary-tree-whose-leaf-nodes-are-connected/
1008
Chapter 164
Input : 1
/ \
2 5
/ \
7 4
/
6
Level l = -1
Output : Yes
Nodes in level -1 are 2 -> 6 which
forms a sorted sequence.
Input: 1
/ \
2 6
\ /
3 4
Level l = 0
Output : Yes
Note that nodes with value 3 and 4
1009
Chapter 164. Find if given vertical level of binary tree is sorted or not
A simple solution is to first do level order traversal of the binary tree and store each vertical
level in different arrays. After this check, if array corresponding to level l is sorted or not.
This solution has large memory requirements that can be reduced.
A efficient solution is to do vertical level order traversal of the binary tree and keep track of
node values in vertical level l of the binary tree. A sequence is sorted if the previous element
is less than or equal to the current element. While doing vertical level order traversal store
previous value and compare current node in vertical level l with this previous value of level
l. If current node value is greater than or equal to the previous value, then repeat the same
procedure until the end of level l. If at any stage current node value is less than previous
value then the level l is not sorted. If we reach at the end of level l then the level is sorted.
Implementation:
1010
Chapter 164. Find if given vertical level of binary tree is sorted or not
return true;
// Variable to store previous
// value in vertical level l.
int prevVal = INT_MIN;
// Variable to store current level
// while traversing tree vertically.
int currLevel;
// Variable to store current node
// while traversing tree vertically.
Node* currNode;
// Declare queue to do vertical order
// traversal. A pair is used as element
// of queue. The first element in pair
// represents the node and the second
// element represents vertical level
// of that node.
queue<pair<Node*, int> > q;
// Insert root in queue. Vertical level
// of root is 0.
q.push(make_pair(root, 0));
// Do vertical order traversal until
// all the nodes are not visited.
while (!q.empty()) {
currNode = q.front().first;
currLevel = q.front().second;
q.pop();
// Check if level of node extracted from
// queue is required level or not. If it
// is the required level then check if
// previous value in that level is less
// than or equal to value of node.
if (currLevel == level) {
if (prevVal <= currNode->key)
prevVal = currNode->key;
else
return false;
}
// If left child is not NULL then push it
// in queue with level reduced by 1.
if (currNode->left)
1011
Chapter 164. Find if given vertical level of binary tree is sorted or not
Output:
Yes
1012
Chapter 164. Find if given vertical level of binary tree is sorted or not
Source
https://www.geeksforgeeks.org/find-given-vertical-level-binary-tree-sorted-not/
1013
Chapter 165
Find if there is a pair in root to a leaf path with sum equals to root’s data - GeeksforGeeks
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in
pair is equal to root’s data. For example, in below tree (2, 3) and (4, 1) are pairs with sum
equals to root’s data.
1014
Chapter 165. Find if there is a pair in root to a leaf path with sum equals to root’s data
The idea is based on hashing and tree traversal. The idea is similar to method 2 of array
pair sum problem.
1015
Chapter 165. Find if there is a pair in root to a leaf path with sum equals to root’s data
1016
Chapter 165. Find if there is a pair in root to a leaf path with sum equals to root’s data
return res;
}
// A wrapper over printPathUtil()
bool isPathSum(Node *root)
{
// create an empty hash table
unordered_set<int> s;
// Recursively check in left and right subtrees.
return printPathUtil(root->left, s, root->data) ||
printPathUtil(root->right, s, root->data);
}
// Driver program to run the case
int main()
{
struct Node *root = newnode(8);
root->left = newnode(5);
root->right = newnode(4);
root->left->left = newnode(9);
root->left->right = newnode(7);
root->left->right->left = newnode(1);
root->left->right->right = newnode(12);
root->left->right->right->right = newnode(2);
root->right->right = newnode(11);
root->right->right->left = newnode(3);
isPathSum(root)? cout << "Yes" : cout << "No";
return 0;
}
Output:
Yes
Time Complexity : O(n) under the assumption that hash search, insert and erase take O(1)
time.
Exercise : Extend the above solution to print all root to leaf paths that have a pair with
sum equals to root’s data.
Source
https://www.geeksforgeeks.org/find-pair-root-leaf-path-sum-equals-roots-data/
1017
Chapter 166
Find largest subtree having identical left and right subtrees - GeeksforGeeks
Given a binary tree, find the largest subtree having identical left and right subtree. Expected
complexity is O(n).
For example,
Input:
50
/ \
10 60
/ \ / \
5 20 70 70
/ \ / \
65 80 65 80
Output:
Largest subtree is rooted at node 60
A simple solution is to consider every node, recursively check if left and right subtrees are
identical using the approach discussed here. Keep track of maximum size such node.
We can save recursive calls. The idea is to do a postorder traversal of given binary tree
and for each node, we store structure of its left and right subtrees. In order to store the
structure of left and right subtree, we use a string. We separate left and right subtree nodes
from current node in the string by using a delimiter. For every encountered node, we update
largest subtree found so far if its left and right subtree structure are similar.
Below is C++ implementation of above idea –
1018
Chapter 166. Find largest subtree having identical left and right subtrees
1019
Chapter 166. Find largest subtree having identical left and right subtrees
1020
Chapter 166. Find largest subtree having identical left and right subtrees
root->left->left = newNode(5);
root->left->right = newNode(20);
root->right->left = newNode(70);
root->right->left->left = newNode(65);
root->right->left->right = newNode(80);
root->right->right = newNode(70);
root->right->right->left = newNode(65);
root->right->right->right = newNode(80);
Node *maxNode = NULL;
int maxSize = largestSubtree(root, maxNode);
cout << "Largest Subtree is rooted at node "
<< maxNode->data << "\nand its size is "
<< maxSize;
return 0;
}
Output :
The worst case time complexity still remains O(n2 ) as we need O(n) time to compare two
strings.
Further Optimization:
We can optimized the space used in above program by using Succinct Encoding of Binary
Tree.
Source
https://www.geeksforgeeks.org/find-largest-subtree-having-identical-left-and-right-subtrees/
1021
Chapter 167
Input : 1
/ \
2 3
/ \ / \
4 5 6 7
Output : 28
As all the tree elements are positive,
the largest subtree sum is equal to
sum of all tree elements.
Input : 1
/ \
-2 3
/ \ \ /
4 5 -6
2
Output : 7
Subtree with largest sum is : -2
/ \
4 5
Also, entire tree sum is also 7.
1022
Chapter 167. Find largest subtree sum in a tree
Approach : Do post order traversal of the binary tree. At every node, find left subtree
value and right subtree value recursively. The value of subtree rooted at current node is
equal to sum of current node value, left node subtree sum and right node subtree sum.
Compare current subtree sum with overall maximum subtree sum so far.
Implementation :
C++
1023
Chapter 167. Find largest subtree sum in a tree
Java
1024
Chapter 167. Find largest subtree sum in a tree
1025
Chapter 167. Find largest subtree sum in a tree
1026
Chapter 167. Find largest subtree sum in a tree
Source
https://www.geeksforgeeks.org/find-largest-subtree-sum-tree/
1027
Chapter 168
In Binary Search Tree, we can find maximum by traversing right pointers until we reach
rightmost node. But in Binary Tree, we must visit every node to figure out maximum. So
the idea is to traverse the given tree and for every node return maximum of 3 values.
1) Node’s data.
2) Maximum in node’s left subtree.
3) Maximum in node’s right subtree.
Below is the implementation of above approach.
C
1028
Chapter 168. Find maximum (or minimum) in Binary Tree
#include <stdlib.h>
#include <limits.h>
// A tree node
struct Node
{
int data;
struct Node* left, *right;
};
// A utility function to create a new node
struct Node* newNode(int data)
{
struct Node* node = (struct Node*)
malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return(node);
}
// Returns maximum value in a given Binary Tree
int findMax(struct Node* root)
{
// Base case
if (root == NULL)
return INT_MIN;
// Return maximum of 3 values:
// 1) Root's data 2) Max in Left Subtree
// 3) Max in right subtree
int res = root->data;
int lres = findMax(root->left);
int rres = findMax(root->right);
if (lres > res)
res = lres;
if (rres > res)
res = rres;
return res;
}
// Driver program
int main(void)
{
struct Node*NewRoot=NULL;
struct Node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
1029
Chapter 168. Find maximum (or minimum) in Binary Tree
root->left->right->left=newNode(1);
root->left->right->right=newNode(11);
root->right->right=newNode(9);
root->right->right->left=newNode(4);
printf ("Maximum element is %d \n", findMax(root));
return 0;
}
Java
1030
Chapter 168. Find maximum (or minimum) in Binary Tree
Output:
Maximum element is 11
Similarly, we can find minimum element in Binary tree by comparing three values. Below
is the function to find minimum in Binary Tree.
1031
Chapter 168. Find maximum (or minimum) in Binary Tree
Java
This article is contributed by Himanshu Gupta. Please write comments if you find any-
thing incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/find-maximum-or-minimum-in-binary-tree/
1032
Chapter 169
Input : 4
/ \
2 -5
/ \ /\
-1 3 -2 6
Output: 36
Explanation :
Product of all nodes of 0'th level is 4
Product of all nodes of 1'th level is -10
Product of all nodes of 0'th level is 36
Hence maximum product is 6
Input : 1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
Output : 160
Explanation :
Product of all nodes of 0'th level is 1
1033
Chapter 169. Find maximum level product in Binary Tree
1034
Chapter 169. Find maximum level product in Binary Tree
1035
Chapter 169. Find maximum level product in Binary Tree
/ \ \
4 5 8
/ \
6 7 */
cout << "Maximum level product is "
<< maxLevelProduct(root) << endl;
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/find-maximum-level-product-binary-tree/
1036
Chapter 170
Input : 4
/ \
2 -5
/ \ /\
-1 3 -2 6
Output: 6
Explanation :
Sum of all nodes of 0'th level is 4
Sum of all nodes of 1'th level is -3
Sum of all nodes of 0'th level is 6
Hence maximum sum is 6
Input : 1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
Output : 17
This problem is a variation of maximum width problem. The idea is to do level order
traversal of tree. While doing traversal, process nodes of different level separately. For
1037
Chapter 170. Find maximum level sum in Binary Tree
every level being processed, compute sum of nodes in the level and keep track of maximum
sum.
1038
Chapter 170. Find maximum level sum in Binary Tree
1039
Chapter 170. Find maximum level sum in Binary Tree
Output :
Source
https://www.geeksforgeeks.org/find-level-maximum-sum-binary-tree/
1040
Chapter 171
Input :
3
/ \
4 6
/ \ / \
-1 -2 5 10
\
8
Output : 14
Vertical level having nodes 6 and 8 has maximum
vertical sum 14.
Input :
1
/ \
5 8
/ \ \
2 -6 3
\ /
-1 -4
\
9
1041
Chapter 171. Find maximum vertical sum in binary tree
Output : 4
A simple solution is to first find vertical level sum of each level starting from minimum
vertical level to maximum vertical level. Finding sum of one vertical level takes O(n) time.
In worst case time complexity of this solution is O(n^2).
An efficient solution is to do level order traversal of given binary tree and update vertical
level sum of each level while doing the traversal. After finding vertical sum of each level
find maximum vertical sum from these values.
Below is the implementation of above approach:
1042
Chapter 171. Find maximum vertical sum in binary tree
int currLev;
// Queue to perform level order traversal.
// Each element of queue is a pair of node
// and its vertical level.
queue<pair<Node*, int> > q;
q.push({ root, 0 });
while (!q.empty()) {
// Extract node at front of queue
// and its vertical level.
root = q.front().first;
currLev = q.front().second;
q.pop();
// Update vertical level sum of
// vertical level to which
// current node belongs to.
verSum[currLev] += root->data;
if (root->left)
q.push({ root->left, currLev - 1 });
if (root->right)
q.push({ root->right, currLev + 1 });
}
// Find maximum vertical level sum.
for (auto it : verSum)
maxSum = max(maxSum, it.second);
return maxSum;
}
// Driver Program to test above functions
int main()
{
/*
3
/ \
4 6
/ \ / \
-1 -2 5 10
\
8
*/
1043
Chapter 171. Find maximum vertical sum in binary tree
Output:
14
Source
https://www.geeksforgeeks.org/find-maximum-vertical-sum-in-binary-tree/
1044
Chapter 172
1045
Chapter 172. Find mirror of a given node in Binary tree
In above tree-
Node 2 and 3 are mirror nodes
Node 4 and 6 are mirror nodes.
We can have a recursive solution for finding mirror nodes. The algorithm is following –
1046
Chapter 172. Find mirror of a given node in Binary tree
1047
Chapter 172. Find mirror of a given node in Binary tree
return left->key;
// first recur external Nodes
int mirror_val = findMirrorRec(target,
left->left,
right->right);
if (mirror_val)
return mirror_val;
// if no mirror found, recur internal Nodes
findMirrorRec(target, left->right, right->left);
}
// interface for mirror search
int findMirror(struct Node* root, int target)
{
if (root == NULL)
return 0;
if (root->key == target)
return target;
return findMirrorRec(target, root->left, root->right);
}
// Driver
int main()
{
struct Node* root = newNode(1);
root-> left = newNode(2);
root->left->left = newNode(4);
root->left->left->right = newNode(7);
root->right = newNode(3);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->left = newNode(8);
root->right->left->right = newNode(9);
// target Node whose mirror have to be searched
int target = root->left->left->key;
int mirror = findMirror(root, target);
if (mirror)
printf("Mirror of Node %d is Node %d\n",
target, mirror);
else
printf("Mirror of Node %d is NULL!\n", target);
}
1048
Chapter 172. Find mirror of a given node in Binary tree
Python
1049
Chapter 172. Find mirror of a given node in Binary tree
# Driver
def main():
root = Node(1)
n1 = Node(2)
n2 = Node(3)
root.lchild = n1
root.rchild = n2
n3 = Node(4)
n4 = Node(5)
n5 = Node(6)
n1.lchild = n3
n2.lchild = n4
n2.rchild = n5
n6 = Node(7)
n7 = Node(8)
n8 = Node(9)
n3.rchild = n6
n4.lchild = n7
n4.rchild = n8
# target node whose mirror have to be searched
target = n3.key
mirror = findMirror(root, target)
print("Mirror of node {} is node {}".format(target, mirror))
if __name__ == '__main__':
main()
Output:
Time Complexity:
Source
https://www.geeksforgeeks.org/find-mirror-given-node-binary-tree/
1050
Chapter 173
1051
Chapter 173. Find multiplication of sums of data of leaves at same levels
Output: 208
First two levels don't have leaves. Third
level has single leaf 8. Last level has four
leaves 1, 11, 4 and 10. Therefore result is
8 * (1 + 11 + 4 + 10)
We strongly recommend you to minimize your browser and try this yourself
first.
One Simple Solution is to recursively compute leaf sum for all level starting from top to
bottom. Then multiply sums of levels which have leaves. Time complexity of this solution
would be O(n2 ).
An Efficient Solution is to use Queue based level order traversal. While doing the traversal,
process all different levels separately. For every processed level, check if it has a leaves. If
it has then compute sum of leaf nodes. Finally return product of all sums.
C++
1052
Chapter 173. Find multiplication of sums of data of leaves at same levels
1053
Chapter 173. Find multiplication of sums of data of leaves at same levels
Java
1054
Chapter 173. Find multiplication of sums of data of leaves at same levels
1055
Chapter 173. Find multiplication of sums of data of leaves at same levels
1056
Chapter 173. Find multiplication of sums of data of leaves at same levels
Output:
This article is contributed by Mohammed Raqeeb. Please write comments if you find any-
thing incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/find-multiplication-of-sums-of-data-of-all-leaves-at-sane-levels/
1057
Chapter 174
Input : N = 4
11
/ \
21 31
/ \
41 51
Output : 31
Explanation: Postorder Traversal of given Binary Tree is 41 51 21 31 11,
so 4th node will be 31.
Input : N = 5
25
/ \
20 30
/ \ / \
18 22 24 32
Output : 32
The idea to solve this problem is to do postorder traversal of the given binary tree and keep
track of the count of nodes visited while traversing the tree and print the current node when
the count becomes equal to N.
1058
Chapter 174. Find n-th node in Postorder traversal of a Binary Tree
1059
Chapter 174. Find n-th node in Postorder traversal of a Binary Tree
// driver code
int main()
{
struct Node* root = createNode(25);
root->left = createNode(20);
root->right = createNode(30);
root->left->left = createNode(18);
root->left->right = createNode(22);
root->right->left = createNode(24);
root->right->right = createNode(32);
int N = 6;
// prints n-th node found
NthPostordernode(root, N);
return 0;
}
Output:
30
Time Complexity: O(n), where n is the number of nodes in the given binary tree.
Auxiliary Space: O(1)
Source
https://www.geeksforgeeks.org/find-n-th-node-in-postorder-traversal-of-a-binary-tree/
1060
Chapter 175
Input: N = 4
11
/ \
21 31
/ \
41 51
Output: 51
Explanation: Preorder Traversal of given Binary Tree is 11 21 41 51 31,
so 4th node will be 51.
Input: N = 5
25
/ \
20 30
/ \ / \
18 22 24 32
Output: 30
The idea to solve this problem is to do preorder traversal of the given binary tree and keep
track of the count of nodes visited while traversing the tree and print the current node when
the count becomes equal to N.
1061
Chapter 175. Find n-th node in Preorder traversal of a Binary Tree
1062
Chapter 175. Find n-th node in Preorder traversal of a Binary Tree
{
// construction of binary tree
struct Node* root = createNode(25);
root->left = createNode(20);
root->right = createNode(30);
root->left->left = createNode(18);
root->left->right = createNode(22);
root->right->left = createNode(24);
root->right->right = createNode(32);
// nth node
int N = 6;
// prints n-th found found
NthPreordernode(root, N);
return 0;
}
Output:
24
Time Complexity: O(n), where n is the number of nodes in the given binary tree.
Auxiliary Space: O(1)
Source
https://www.geeksforgeeks.org/find-n-th-node-in-preorder-traversal-of-a-binary-tree/
1063
Chapter 176
Input : n = 4
10
/ \
20 30
/ \
40 50
Output : 10
Inorder Traversal is : 40 20 50 10 30
Input : n = 3
7
/ \
2 3
/ \
8 5
Output : 8
Inorder: 2 7 8 3 5
3th node is 8
We do simple Inorder Traversal. While doing the traversal, we keep track of count of nodes
visited so far. When count becomes n, we print the node.
1064
Chapter 176. Find n-th node of inorder traversal
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
int data;
struct Node* left;
struct Node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
/* Given a binary tree, print its nth nodes of inorder*/
void NthInorder(struct Node* node, int n)
{
static int count = 0;
if (node == NULL)
return;
if (count <= n) {
/* first recur on left child */
NthInorder(node->left, n);
count++;
// when count = n then print element
if (count == n)
printf("%d ", node->data);
/* now recur on right child */
NthInorder(node->right, n);
}
}
/* Driver program to test above functions*/
int main()
1065
Chapter 176. Find n-th node of inorder traversal
{
struct Node* root = newNode(10);
root->left = newNode(20);
root->right = newNode(30);
root->left->left = newNode(40);
root->left->right = newNode(50);
int n = 4;
NthInorder(root, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-n-th-node-inorder-traversal/
1066
Chapter 177
10
/ \
2 6
/ \ \
8 4 5
Solution: The idea is to do level order traversal of given Binary Tree. When we find the
given key, we just check if the next node in level order traversal is of same level, if yes, we
return the next node, otherwise return NULL.
C++
1067
Chapter 177. Find next right node of a given key
1068
Chapter 177. Find next right node of a given key
}
if (node->right != NULL)
{
qn.push(node->right);
ql.push(level+1);
}
}
// We reach here if given key x doesn't exist in tree
return NULL;
}
// Utility function to create a new tree node
node* newNode(int key)
{
node *temp = new node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to test above functions
void test(node *root, int k)
{
node *nr = nextRight(root, k);
if (nr != NULL)
cout << "Next Right of " << k << " is " << nr->key << endl;
else
cout << "No next right node found for " << k << endl;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree given in the above example
node *root = newNode(10);
root->left = newNode(2);
root->right = newNode(6);
root->right->right = newNode(5);
root->left->left = newNode(8);
root->left->right = newNode(4);
test(root, 10);
test(root, 2);
test(root, 6);
test(root, 5);
test(root, 8);
test(root, 4);
1069
Chapter 177. Find next right node of a given key
return 0;
}
Java
1070
Chapter 177. Find next right node of a given key
1071
Chapter 177. Find next right node of a given key
Python
1072
Chapter 177. Find next right node of a given key
level = 0
# Enqueue root and its level
qn.append(root)
q1.append(level)
# Standard BFS loop
while(len(qn) > 0):
# Dequeu an node from qn and its level from q1
node = qn.pop(0)
level = q1.pop(0)
# If the dequeued node has the given key k
if node.key == k :
# If there are no more items in queue or given
# node is the rightmost node of its level,
# then return None
if (len(q1) == 0 or q1[0] != level):
return None
# Otherwise return next node from queue of nodes
return qn[0]
# Standard BFS steps: enqueue children of this node
if node.left is not None:
qn.append(node.left)
q1.append(level+1)
if node.right is not None:
qn.append(node.right)
q1.append(level+1)
# We reach here if given key x doesn't exist in tree
return None
def test(root, k):
nr = nextRight(root, k)
if nr is not None:
print "Next Right of " + str(k) + " is " + str(nr.key)
else:
print "No next right node found for " + str(k)
# Driver program to test above function
root = Node(10)
root.left = Node(2)
1073
Chapter 177. Find next right node of a given key
root.right = Node(6)
root.right.right = Node(5)
root.left.left = Node(8)
root.left.right = Node(4)
test(root, 10)
test(root, 2)
test(root, 6)
test(root, 5)
test(root, 8)
test(root, 4)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time Complexity: The above code is a simple BFS traversal code which visits every
enqueue and dequeues a node at most once. Therefore, the time complexity is O(n) where
n is the number of nodes in the given binary tree.
Exercise: Write a function to find left node of a given node. If there is no node on the left
side, then return NULL.
Source
https://www.geeksforgeeks.org/find-next-right-node-of-a-given-key/
1074
Chapter 178
10
/ \
2 6
/ \ \
8 4 5
Input : 2
Output : 6
Input : 4
Output : 5
In our previous post we have discussed about a solution using Level Order Traversal. In
this post we will discuss about a solution based on Preorder traversal which takes constant
auxiliary space.
The idea is to traverse the given tree using preorder traversal and search for the given key.
Once we found the given key, we will mark the level number for this key. Now the next
node we will find at the same level is the required node which is at the right of given key.
Below is the implementation of above idea:
1075
Chapter 178. Find next right node of a given key | Set 2
1076
Chapter 178. Find next right node of a given key | Set 2
1077
Chapter 178. Find next right node of a given key | Set 2
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/find-next-right-node-given-key-set-2/
1078
Chapter 179
1
/ \
2 3
/ \ \
4 6 5
/ \ \
7 9 8
/ \
10 12
Input : Given above tree with parent pointer and node 10
Output : 12
Idea is to find out first right child of nearest ancestor which is neither the current node nor
parent of current node, keep track of level in those while going up. then, iterate through
that node first left child, if left is not there then, right child and if level becomes 0, then,
this is the next right sibling of the given node.
In above case if given node is 7, we will end up with 6 to find right child which doesn’t have
any child.
In this case we need to recursively call for right sibling with the current level, so that we
case reach 8.
C++
1079
Chapter 179. Find right sibling of a binary tree with parent pointers
1080
Chapter 179. Find right sibling of a binary tree with parent pointers
1081
Chapter 179. Find right sibling of a binary tree with parent pointers
return 0;
}
Java
1082
Chapter 179. Find right sibling of a binary tree with parent pointers
1083
Chapter 179. Find right sibling of a binary tree with parent pointers
Output:
12
Source
https://www.geeksforgeeks.org/find-right-sibling-binary-tree-parent-pointers/
1084
Chapter 180
Find root of the tree where children id sum for every node is given - GeeksforGeeks
Consider a binary tree whose nodes have ids from 1 to n where n is number of nodes in the
tree. The tree is given as a collection of n pairs, where every pair represents node id and
sum of children ids.
Examples:
Input : 1 5
2 0
3 0
4 0
5 5
6 5
Output: 6
Explanation: In this case, two trees can
be made as follows and 6 is the root node.
6 6
\ / \
5 1 4
/ \ \
1 4 5
/ \ / \
2 3 2 3
Input : 4 0
Output: 4
1085
Chapter 180. Find root of the tree where children id sum for every node is given
At first sight this question appears to be a typical question of tree data structure but it
can be solved as follows.
Every node id appears in children sum except root. So if we do sum of all ids and subtract
it from sum of all children sums, we get root.
Output:
Source
https://www.geeksforgeeks.org/find-root-tree-children-id-sum-every-node-given/
1086
Chapter 181
The idea is to traverse the tree, starting from root. For every node, check if its left subtree
is a leaf. If it is, then add it to the result.
Following is the implementation of above idea.
C++
1087
Chapter 181. Find sum of all left leaves in a given Binary Tree
1088
Chapter 181. Find sum of all left leaves in a given Binary Tree
// Recur for right child of root and update res
res += leftLeavesSum(root->right);
}
// return result
return res;
}
/* Driver program to test above functions*/
int main()
{
// Let us a construct the Binary Tree
struct Node *root = newNode(20);
root->left = newNode(9);
root->right = newNode(49);
root->right->left = newNode(23);
root->right->right = newNode(52);
root->right->right->left = newNode(50);
root->left->left = newNode(5);
root->left->right = newNode(12);
root->left->right->right = newNode(12);
cout << "Sum of left leaves is "
<< leftLeavesSum(root);
return 0;
}
Java
1089
Chapter 181. Find sum of all left leaves in a given Binary Tree
{
if (node == null)
return false;
if (node.left == null && node.right == null)
return true;
return false;
}
// This function returns sum of all left leaves in a given
// binary tree
int leftLeavesSum(Node node)
{
// Initialize result
int res = 0;
// Update result if root is not NULL
if (node != null)
{
// If left of root is NULL, then add key of
// left child
if (isLeaf(node.left))
res += node.left.data;
else // Else recur for left child of root
res += leftLeavesSum(node.left);
// Recur for right child of root and update res
res += leftLeavesSum(node.right);
}
// return result
return res;
}
// Driver program
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(20);
tree.root.left = new Node(9);
tree.root.right = new Node(49);
tree.root.left.right = new Node(12);
tree.root.left.left = new Node(5);
tree.root.right.left = new Node(23);
tree.root.right.right = new Node(52);
tree.root.left.right.right = new Node(12);
tree.root.right.right.left = new Node(50);
System.out.println("The sum of leaves is " +
1090
Chapter 181. Find sum of all left leaves in a given Binary Tree
tree.leftLeavesSum(tree.root));
}
}
// This code is contributed by Mayank Jaiswal
Python
1091
Chapter 181. Find sum of all left leaves in a given Binary Tree
Output:
Time complexity of the above solution is O(n) where n is number of nodes in Binary Tree.
Following is Another Method to solve the above problem. This solution passes in a sum
variable as an accumulator. When a left leaf is encountered, the leaf’s data is added to sum.
Time complexity of this method is also O(n). Thanks to Xin Tong (geeksforgeeks userid
trent.tong) for suggesting this method.
C++
1092
Chapter 181. Find sum of all left leaves in a given Binary Tree
return node;
}
/* Pass in a sum variable as an accumulator */
void leftLeavesSumRec(Node *root, bool isleft, int *sum)
{
if (!root) return;
// Check whether this node is a leaf node and is left.
if (!root->left && !root->right && isleft)
*sum += root->key;
// Pass 1 for left and 0 for right
leftLeavesSumRec(root->left, 1, sum);
leftLeavesSumRec(root->right, 0, sum);
}
// A wrapper over above recursive function
int leftLeavesSum(Node *root)
{
int sum = 0; //Initialize result
// use the above recursive function to evaluate sum
leftLeavesSumRec(root, 0, &sum);
return sum;
}
/* Driver program to test above functions*/
int main()
{
// Let us construct the Binary Tree shown in the
// above figure
int sum = 0;
struct Node *root = newNode(20);
root->left = newNode(9);
root->right = newNode(49);
root->right->left = newNode(23);
root->right->right = newNode(52);
root->right->right->left = newNode(50);
root->left->left = newNode(5);
root->left->right = newNode(12);
root->left->right->right = newNode(12);
cout << "Sum of left leaves is " << leftLeavesSum(root) << endl;
return 0;
}
1093
Chapter 181. Find sum of all left leaves in a given Binary Tree
Java
1094
Chapter 181. Find sum of all left leaves in a given Binary Tree
return suum.sum;
}
// Driver program
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(20);
tree.root.left = new Node(9);
tree.root.right = new Node(49);
tree.root.left.right = new Node(12);
tree.root.left.left = new Node(5);
tree.root.right.left = new Node(23);
tree.root.right.right = new Node(52);
tree.root.left.right.right = new Node(12);
tree.root.right.right.left = new Node(50);
System.out.println("The sum of leaves is " +
tree.leftLeavesSum(tree.root));
}
}
// This code is contributed by Mayank Jaiswal
Python
1095
Chapter 181. Find sum of all left leaves in a given Binary Tree
# A wrapper over above recursive function
def leftLeavesSum(root):
summ = [0] # initialize result
# Use the above recursive fucntion to evaluate sum
leftLeavesSumRec(root, 0, summ)
return summ[0]
# Driver program to test above function
# Let us construct the Binary Tree shown in the
# above figure
root = Node(20);
root.left= Node(9);
root.right = Node(49);
root.right.left = Node(23);
root.right.right= Node(52);
root.right.right.left = Node(50);
root.left.left = Node(5);
root.left.right = Node(12);
root.left.right.right = Node(12);
print "Sum of left leaves is", leftLeavesSum(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Iterative Approach :
This is the Iterative Way to find the sum of the left leaves.
Idea is to perform Depth-First Traversal on the tree (either Inorder, Preorder or Postorder)
using a stack and checking if the Left Child is a Leaf node. If it is, then add the nodes value
to the sum variable
1096
Chapter 181. Find sum of all left leaves in a given Binary Tree
self.key = key
self.left = None
self.right = None
# Return the sum of left leaf nodes
def sumOfLeftLeaves(root):
if(root is None):
return
# Using a stack for Depth-First Traversal of the tree
stack = []
stack.append(root)
# sum holds the sum of all the left leaves
sum = 0
while len(stack) > 0:
currentNode = stack.pop()
if currentNode.left is not None:
stack.append(currentNode.left)
# Check if currentNode's left child is a leaf node
if currentNode.left.left is None and currentNode.left.right is None:
# if currentNode is a leaf, add its data to the sum
sum = sum + currentNode.left.data
if currentNode.right is not None:
stack.append(currentNode.right)
return sum
# Driver Code
root = Tree(20);
root.left= Tree(9);
root.right = Tree(49);
root.right.left = Tree(23);
root.right.right= Tree(52);
root.right.right.left = Tree(50);
root.left.left = Tree(5);
root.left.right = Tree(12);
root.left.right.right = Tree(12);
print('Sum of left leaves is {}'.format(sumOfLeftLeaves(root)))
Output:
1097
Chapter 181. Find sum of all left leaves in a given Binary Tree
Source
https://www.geeksforgeeks.org/find-sum-left-leaves-given-binary-tree/
1098
Chapter 182
Find sum of all nodes of the given perfect binary tree - GeeksforGeeks
Given a positive integer L which represents the number of levels in a perfect binary tree.
Given that the leaf nodes in this perfect binary tree are numbered starting from 1 to n,
where n is the number of leaf nodes. And the parent node is the sum of the two child nodes.
Our task is to write a program to print the sum of all of the nodes of this perfect binary
tree.
Examples:
Input : L = 3
Output : 30
Explanation : Tree will be - 10
/ \
3 7
/ \ / \
1 2 3 4
Input : L = 2
Output : 6
Explanation : Tree will be - 3
/ \
1 2
Naive Approach: The simplest solution is to first generate the value of all of the nodes of
the perfect binary tree and then calculate the sum of all of the nodes. We can first generate
all of the leaf nodes and then proceed in the bottom-up fashion to generate rest of the nodes.
We know that in a perfect binary tree, the number of leaf nodes can be given by 2L-1 , where
1099
Chapter 182. Find sum of all nodes of the given perfect binary tree
L is the number of levels. The number of nodes in a perfect binary tree as we move upward
from the bottom will get decreased by half.
Below is the implementation of above idea:
C++
#include <bits/stdc++.h>
using namespace std;
// function to find sum of all of the nodes
// of given perfect binary tree
int sumNodes(int l)
{
// no of leaf nodes
int leafNodeCount = pow(2, l - 1);
// list of vector to store nodes of
// all of the levels
vector<int> vec[l];
// store the nodes of last level
// i.e., the leaf nodes
for (int i = 1; i <= leafNodeCount; i++)
vec[l - 1].push_back(i);
// store nodes of rest of the level
// by moving in bottom-up manner
for (int i = l - 2; i >= 0; i--) {
int k = 0;
// loop to claculate values of parent nodes
// from the children nodes of lower level
while (k < vec[i + 1].size() - 1) {
// store the value of parent node as
// sum of children nodes
vec[i].push_back(vec[i + 1][k] +
vec[i + 1][k + 1]);
k += 2;
}
}
int sum = 0;
// traverse the list of vector
// and calculate the sum
for (int i = 0; i < l; i++) {
1100
Chapter 182. Find sum of all nodes of the given perfect binary tree
Java
// Java program to implement
// the above approach
import java.util.*;
class GFG
{
// function to find sum of
// all of the nodes of given
// perfect binary tree
static int sumNodes(int l)
{
// no of leaf nodes
int leafNodeCount = (int)Math.pow(2, l – 1);
// list of vector to store
// nodes of all of the levels
Vector> vec = new Vector>();
//initilize
for (int i = 1; i <= l; i++) vec.add(new Vector());
// store the nodes of last level
// i.e., the leaf nodes
for (int i = 1;
i <= leafNodeCount; i++) vec.get(l - 1).add(i); // store nodes of rest of // the level by
moving in // bottom-up manner for (int i = l - 2; i >= 0; i–)
{
int k = 0;
// loop to claculate values
// of parent nodes from the
// children nodes of lower level
1101
Chapter 182. Find sum of all nodes of the given perfect binary tree
while (k < vec.get(i + 1).size() - 1) { // store the value of parent // node as sum of children
nodes vec.get(i).add(vec.get(i + 1).get(k) + vec.get(i + 1).get(k + 1)); k += 2; } } int sum
= 0; // traverse the list of vector // and calculate the sum for (int i = 0; i < l; i++) { for
(int j = 0; j < vec.get(i).size(); j++) sum += vec.get(i).get(j); } return sum; } // Driver
Code public static void main(String args[]) { int l = 3; System.out.println(sumNodes(l)); }
} // This code is contributed // by Arnab Kundu [tabbyending] Output:
30
Time Complexity: O(n), where n is the total number of nodes in the perfect binary tree.
Efficient Approach: An efficient approach is to observe that we only need to find the sum
of all of the nodes. We can easily get the sum of all nodes at the last level using the formula
of sum of first n natural numbers. Also, it can be seen that, as it is a perfect binary tree
and parent nodes will be the sum of children nodes so the sum of nodes at all of the levels
will be same. Therefore, we just need to find the sum of nodes at last level and multiply it
by the total number of levels.
Below is the implementation of above idea:
C++
#include <bits/stdc++.h>
using namespace std;
// function to find sum of all of the nodes
// of given perfect binary tree
int sumNodes(int l)
{
// no of leaf nodes
int leafNodeCount = pow(2, l - 1);
int sumLastLevel = 0;
// sum of nodes at last level
sumLastLevel = (leafNodeCount * (leafNodeCount + 1)) / 2;
// sum of all nodes
int sum = sumLastLevel * l;
return sum;
}
// Driver Code
int main()
{
int l = 3;
1102
Chapter 182. Find sum of all nodes of the given perfect binary tree
Java
Python3
1103
Chapter 182. Find sum of all nodes of the given perfect binary tree
C#
1104
Chapter 182. Find sum of all nodes of the given perfect binary tree
// sum of all nodes
double sum = sumLastLevel * l;
return sum;
}
// Driver Code
public static void Main()
{
int l = 3;
Console.Write(sumNodes(l));
}
}
// This code is contributed by
// Manish Shaw (manishshaw1)
PHP
<?php
// PHP code to find sum of all nodes
// of the given perfect binary tree
// function to find sum of
// all of the nodes of given
// perfect binary tree
function sumNodes($l)
{
// no of leaf nodes
$leafNodeCount = ($l - 1) *
($l - 1);
$sumLastLevel = 0;
// sum of nodes at last level
$sumLastLevel = ($leafNodeCount *
($leafNodeCount + 1)) / 2;
// sum of all nodes
$sum = $sumLastLevel * $l;
return $sum;
}
// Driver Code
$l = 3;
1105
Chapter 182. Find sum of all nodes of the given perfect binary tree
echo (sumNodes($l));
// This code is contributed by
// Manish Shaw (manishshaw1)
?>
Output:
30
Source
https://www.geeksforgeeks.org/find-sum-nodes-given-perfect-binary-tree/
1106
Chapter 183
Input :
1
/ \
2 3
/ \ \
4 5 8
\ / \
2 6 7
Output :
sum = 2 + 5 + 7 = 14
The idea is to traverse the tree starting from the root and check if the node is the leaf node
or not. If the node is the right leaf than add data of right leaf to sum variable.
Following is the implementation for the same.
C++
1107
Chapter 183. Find sum of all right leaves in a given Binary Tree
1108
Chapter 183. Find sum of all right leaves in a given Binary Tree
int sum = 0;
rightLeafSum(root, &sum);
cout << sum << endl;
return 0;
}
Java
1109
Chapter 183. Find sum of all right leaves in a given Binary Tree
}
// Driver Code
public static void main(String args[])
{
//contruct binary tree
Node root = addNode(1);
root.left = addNode(2);
root.left.left = addNode(4);
root.left.right = addNode(5);
root.left.left.right = addNode(2);
root.right = addNode(3);
root.right.right = addNode(8);
root.right.right.left = addNode(6);
root.right.right.right = addNode(7);
// variable to store sum
// of right leaves
sum = 0;
rightLeafSum(root);
System.out.println( sum );
}
}
// This code is contributed by Arnab Kundu
Output:
14
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/find-sum-right-leaves-given-binary-tree/
1110
Chapter 184
Method 1 : The idea is to do Inorder traversal of given binary tree. While doing Inorder
traversal, we pass level of current node also. We keep track of maximum level seen so far
and value of deepest node seen so far.
1111
Chapter 184. Find the Deepest Node in a Binary Tree
1112
Chapter 184. Find the Deepest Node in a Binary Tree
Output:
1113
Chapter 184. Find the Deepest Node in a Binary Tree
left = NULL;
right = NULL;
}
};
// Utility function to find height
// of a tree, rooted at 'root'.
int height(Node* root)
{
if(!root) return 0;
int leftHt = height(root->left);
int rightHt = height(root->right);
return max(leftHt, rightHt) + 1;
}
// levels : current Level
// Utility function to print all
// nodes at a given level.
void deepestNode(Node* root, int levels)
{
if(!root) return;
if(levels == 1)
cout << root->data;
else if(levels > 1)
{
deepestNode(root->left, levels - 1);
deepestNode(root->right, levels - 1);
}
}
// Driver program
int main()
{
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->right->left = new Node(5);
root->right->right = new Node(6);
root->right->left->right = new Node(7);
root->right->right->right = new Node(8);
root->right->left->right->left = new Node(9);
// Calculating height of tree
1114
Chapter 184. Find the Deepest Node in a Binary Tree
Output:
Source
https://www.geeksforgeeks.org/find-deepest-node-binary-tree/
1115
Chapter 185
Examples:
Input : k = 18
Output : 17
Input : k = 12
1116
Chapter 185. Find the closest element in Binary Search Tree
Output : 9
A simple solution for this problem is to store Inorder traversal of given binary search tree
in an auxiliary array and then by taking absolute difference of each element find the node
having minimum absolute difference with given target value K in linear time.
An efficient solution for this problem is to take advantage of characteristics of BST. Here
is the algorithm to solve this problem :
• If target value K is present in given BST, then it’s the node having minimum absolute
difference.
• If target value K is less than the value of current node then move to the left child.
• If target value K is greater than the value of current node then move to the right child.
17
Source
https://www.geeksforgeeks.org/find-closest-element-binary-search-tree/
1117
Chapter 186
A
/ \
B C
/ \
E F
/ \
G H
/ \ /
I J K
We strongly recommend to minimize your browser and try this yourself first
The main point to note here is that a closest key can either be a descendent of given key or
can be reached through one of the ancestors.
The idea is to traverse the given tree in preorder and keep track of ancestors in an array.
When we reach the given key, we evaluate distance of the closest leaf in subtree rooted with
given key. We also traverse all ancestors one by one and find distance of the closest leaf in
the subtree rooted with ancestor. We compare all distances and return minimum.
C++
1118
Chapter 186. Find the closest leaf in a Binary Tree
// A C++ program to find the closesr leaf of a given key in Binary Tree
#include <iostream>
#include <climits>
using namespace std;
/* A binary tree Node has key, pocharer to left and right children */
struct Node
{
char key;
struct Node* left, *right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pocharers. */
Node *newNode(char k)
{
Node *node = new Node;
node->key = k;
node->right = node->left = NULL;
return node;
}
// A utility function to find minimum of x and y
int getMin(int x, int y)
{
return (x < y)? x :y;
}
// A utility function to find distance of closest leaf of the tree
// rooted under given root
int closestDown(struct Node *root)
{
// Base cases
if (root == NULL)
return INT_MAX;
if (root->left == NULL && root->right == NULL)
return 0;
// Return minimum of left and right, plus one
return 1 + getMin(closestDown(root->left), closestDown(root->right));
}
// Returns distance of the cloest leaf to a given key 'k'. The array
// ancestors is used to keep track of ancestors of current node and
// 'index' is used to keep track of curremt index in 'ancestors[]'
int findClosestUtil(struct Node *root, char k, struct Node *ancestors[],
int index)
{
1119
Chapter 186. Find the closest leaf in a Binary Tree
1120
Chapter 186. Find the closest leaf in a Binary Tree
root->right->left->left->right = newNode('J');
root->right->right->right = newNode('H');
root->right->right->right->left = newNode('K');
char k = 'H';
cout << "Distace of the closest key from " << k << " is "
<< findClosest(root, k) << endl;
k = 'C';
cout << "Distace of the closest key from " << k << " is "
<< findClosest(root, k) << endl;
k = 'E';
cout << "Distace of the closest key from " << k << " is "
<< findClosest(root, k) << endl;
k = 'B';
cout << "Distace of the closest key from " << k << " is "
<< findClosest(root, k) << endl;
return 0;
}
Java
1121
Chapter 186. Find the closest leaf in a Binary Tree
1122
Chapter 186. Find the closest leaf in a Binary Tree
{
// Create an array to store ancestors
// Assumptiom: Maximum height of tree is 100
Node ancestors[] = new Node[100];
return findClosestUtil(node, k, ancestors, 0);
}
// Driver program to test for above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node('A');
tree.root.left = new Node('B');
tree.root.right = new Node('C');
tree.root.right.left = new Node('E');
tree.root.right.right = new Node('F');
tree.root.right.left.left = new Node('G');
tree.root.right.left.left.left = new Node('I');
tree.root.right.left.left.right = new Node('J');
tree.root.right.right.right = new Node('H');
tree.root.right.right.right.left = new Node('H');
char k = 'H';
System.out.println("Distace of the closest key from " + k + " is "
+ tree.findClosest(tree.root, k));
k = 'C';
System.out.println("Distace of the closest key from " + k + " is "
+ tree.findClosest(tree.root, k));
k = 'E';
System.out.println("Distace of the closest key from " + k + " is "
+ tree.findClosest(tree.root, k));
k = 'B';
System.out.println("Distace of the closest key from " + k + " is "
+ tree.findClosest(tree.root, k));
}
}
// This code has been contributed by Mayank Jaiswal
Python
1123
Chapter 186. Find the closest leaf in a Binary Tree
1124
Chapter 186. Find the closest leaf in a Binary Tree
Output:
The above code can be optimized by storing the left/right information also in ancestor
1125
Chapter 186. Find the closest leaf in a Binary Tree
array. The idea is, if given key is in left subtree of an ancestors, then there is no point to
call closestDown(). Also, the loop can that traverses ancestors array can be optimized to
not traverse ancestors which are at more distance than current result.
Exercise:
Extend the above solution to print not only distance, but the key of closest leaf also.
This article is contributed by Shubham. Please write comments if you find anything incor-
rect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/find-closest-leaf-binary-tree/
1126
Chapter 187
Find the largest BST subtree in a given Binary Tree | Set 1 - GeeksforGeeks
Given a Binary Tree, write a function that returns the size of the largest subtree which is
also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size
of whole tree.
Examples:
Input:
5
/ \
2 4
/ \
1 3
Output: 3
The following subtree is the maximum size BST subtree
2
/ \
1 3
Input:
50
/ \
30 60
/ \ / \
5 20 45 70
/ \
1127
Chapter 187. Find the largest BST subtree in a given Binary Tree | Set 1
65 80
Output: 5
The following subtree is the maximum size BST subtree
60
/ \
45 70
/ \
65 80
/*
See https://www.geeksforgeeks.org/write-a-c-program-to-calculate-size-of-a-tree/ for implementa
See Method 3 of https://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not
implementation of isBST()
max() returns maximum of two integers
*/
int largestBST(struct node *root)
{
if (isBST(root))
return size(root);
else
return max(largestBST(root->left), largestBST(root->right));
}
Time Complexity: The worst case time complexity of this method will be O(n^2). Consider
a skewed tree for worst case analysis.
1128
Chapter 187. Find the largest BST subtree in a given Binary Tree | Set 1
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
int largestBSTUtil(struct node* node, int *min_ref, int *max_ref,
int *max_size_ref, bool *is_bst_ref);
/* Returns size of the largest BST subtree in a Binary Tree
(efficient version). */
int largestBST(struct node* node)
{
// Set the initial values for calling largestBSTUtil()
int min = INT_MAX; // For minimum value in right subtree
int max = INT_MIN; // For maximum value in left subtree
int max_size = 0; // For size of the largest BST
bool is_bst = 0;
1129
Chapter 187. Find the largest BST subtree in a given Binary Tree | Set 1
1130
Chapter 187. Find the largest BST subtree in a given Binary Tree | Set 1
1131
Chapter 187. Find the largest BST subtree in a given Binary Tree | Set 1
root->right->right = newNode(70);
root->right->right->left = newNode(65);
root->right->right->right = newNode(80);
/* The complete tree is not BST as 45 is in right subtree of 50.
The following subtree is the largest BST
60
/ \
55 70
/ / \
45 65 80
*/
printf(" Size of the largest BST is %d", largestBST(root));
getchar();
return 0;
}
Java
1132
Chapter 187. Find the largest BST subtree in a given Binary Tree | Set 1
(efficient version). */
int largestBST(Node node) {
largestBSTUtil(node, val, val, val, val);
return val.max_size;
}
/* largestBSTUtil() updates *max_size_ref for the size of the largest BST
subtree. Also, if the tree rooted with node is non-empty and a BST,
then returns size of the tree. Otherwise returns 0.*/
int largestBSTUtil(Node node, Value min_ref, Value max_ref,
Value max_size_ref, Value is_bst_ref) {
/* Base Case */
if (node == null) {
is_bst_ref.is_bst = true; // An empty tree is BST
return 0; // Size of the BST is 0
}
int min = Integer.MAX_VALUE;
/* A flag variable for left subtree property
i.e., max(root->left) < root->data */
boolean left_flag = false;
/* A flag variable for right subtree property
i.e., min(root->right) > root->data */
boolean right_flag = false;
int ls, rs; // To store sizes of left and right subtrees
/* Following tasks are done by recursive call for left subtree
a) Get the maximum value in left subtree (Stored in *max_ref)
b) Check whether Left Subtree is BST or not (Stored in *is_bst_ref)
c) Get the size of maximum size BST in left subtree (updates *max_size) */
max_ref.max = Integer.MIN_VALUE;
ls = largestBSTUtil(node.left, min_ref, max_ref, max_size_ref, is_bst_ref);
if (is_bst_ref.is_bst == true && node.data > max_ref.max) {
left_flag = true;
}
/* Before updating *min_ref, store the min value in left subtree. So that we
have the correct minimum value for this subtree */
min = min_ref.min;
/* The following recursive call does similar (similar to left subtree)
task for right subtree */
1133
Chapter 187. Find the largest BST subtree in a given Binary Tree | Set 1
min_ref.min = Integer.MAX_VALUE;
rs = largestBSTUtil(node.right, min_ref, max_ref, max_size_ref, is_bst_ref);
if (is_bst_ref.is_bst == true && node.data < min_ref.min) {
right_flag = true;
}
// Update min and max values for the parent recursive calls
if (min < min_ref.min) {
min_ref.min = min;
}
if (node.data < min_ref.min) // For leaf nodes
{
min_ref.min = node.data;
}
if (node.data > max_ref.max) {
max_ref.max = node.data;
}
/* If both left and right subtrees are BST. And left and right
subtree properties hold for this node, then this tree is BST.
So return the size of this tree */
if (left_flag && right_flag) {
if (ls + rs + 1 > max_size_ref.max_size) {
max_size_ref.max_size = ls + rs + 1;
}
return ls + rs + 1;
} else {
//Since this subtree is not BST, set is_bst flag for parent calls
is_bst_ref.is_bst = false;
return 0;
}
}
public static void main(String[] args) {
/* Let us construct the following Tree
50
/ \
10 60
/ \ / \
5 20 55 70
/ / \
45 65 80
*/
BinaryTree tree = new BinaryTree();
tree.root = new Node(50);
tree.root.left = new Node(10);
tree.root.right = new Node(60);
1134
Chapter 187. Find the largest BST subtree in a given Binary Tree | Set 1
Time Complexity: O(n) where n is the number of nodes in the given Binary Tree.
Source
https://www.geeksforgeeks.org/find-the-largest-subtree-in-a-tree-that-is-also-a-bst/
1135
Chapter 188
The idea is to traverse the tree along depth recursively and return the nodes once the
required level is reached and then return the maximum of left and right subtrees for each
1136
Chapter 188. Find the maximum node at a given level in a binary tree
subsequent call. So that the last call will return the node with maximum value among all
nodes at the given level.
Below is the step by step algorithm:
1. Perform DFS traversal and every time decrease the value of level by 1 and keep travers-
ing to the left and right subtrees recursively.
2. When value of level becomes 0, it means we are on the given level, then return root-
>data.
3. Find the maximum between the two values returned by left and right subtrees and
return the maximum.
C++
1137
Chapter 188. Find the maximum node at a given level in a binary tree
Java
1138
Chapter 188. Find the maximum node at a given level in a binary tree
// Tree node
static class Node
{
int data;
Node left, right;
}
// Utility function to
// create a new Node
static Node newNode(int val)
{
Node temp = new Node();
temp.left = null;
temp.right = null;
temp.data = val;
return temp;
}
// function to find
// the maximum value
// at given level
static int maxAtLevel(Node root, int level)
{
// If the tree is empty
if (root == null)
return 0;
// if level becomes 0,
// it means we are on
// any node at the given level
if (level == 0)
return root.data;
int x = maxAtLevel(root.left, level - 1);
int y = maxAtLevel(root.right, level - 1);
// return maximum of two
return Math.max(x, y);
}
// Driver code
public static void main(String args[])
{
// Creating the tree
Node root = null;
root = newNode(45);
root.left = newNode(46);
1139
Chapter 188. Find the maximum node at a given level in a binary tree
root.left.left = newNode(18);
root.left.left.left = newNode(16);
root.left.left.right = newNode(23);
root.left.right = newNode(17);
root.left.right.left = newNode(24);
root.left.right.right = newNode(21);
root.right = newNode(15);
root.right.left = newNode(22);
root.right.left.left = newNode(37);
root.right.left.right = newNode(41);
root.right.right = newNode(19);
root.right.right.left = newNode(49);
root.right.right.right = newNode(29);
int level = 3;
System.out.println(maxAtLevel(root, level));
}
}
// This code is contributed
// by Arnab Kundu
Output:
49
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/find-the-maximum-node-at-a-given-level-in-a-binary-tree/
1140
Chapter 189
Find the maximum path sum between two leaves of a binary tree - GeeksforGeeks
Given a binary tree in which each node element contains a number. Find the maximum
possible sum from one leaf node to another.
The maximum sum path may or may not go through root. For example, in the following
binary tree, the maximum sum is 27(3 + 6 + 9 + 0 – 1 + 10). Expected time complexity
is O(n).
If one side of root is empty, then function should return minus infinite (INT_MIN in case
of C/C++)
A simple solution is to traverse the tree and do following for every traversed node X.
1) Find maximum sum from leaf to root in left subtree of X (we can use this post for this
and next steps)
1141
Chapter 189. Find the maximum path sum between two leaves of a binary tree
1142
Chapter 189. Find the maximum path sum between two leaves of a binary tree
1143
Chapter 189. Find the maximum path sum between two leaves of a binary tree
root->left->right = newNode(1);
root->left->left->left = newNode(2);
root->left->left->right = newNode(6);
root->right->left = newNode(3);
root->right->right = newNode(9);
root->right->right->right= newNode(0);
root->right->right->right->left= newNode(4);
root->right->right->right->right= newNode(-1);
root->right->right->right->right->left= newNode(10);
cout << "Max pathSum of the given binary tree is "
<< maxPathSum(root);
return 0;
}
Java
1144
Chapter 189. Find the maximum path sum between two leaves of a binary tree
1145
Chapter 189. Find the maximum path sum between two leaves of a binary tree
Python
1146
Chapter 189. Find the maximum path sum between two leaves of a binary tree
1147
Chapter 189. Find the maximum path sum between two leaves of a binary tree
Output:
Source
https://www.geeksforgeeks.org/find-maximum-path-sum-two-leaves-binary-tree/
1148
Chapter 190
Find the maximum sum leaf to root path in a Binary Tree - GeeksforGeeks
Source
https://www.geeksforgeeks.org/find-the-maximum-sum-path-in-a-binary-tree/
1149
Chapter 191
Find the node with minimum value in a Binary Search Tree - GeeksforGeeks
This is quite simple. Just traverse the node from root to left recursively until left is NULL.
The node whose left is NULL is the node with minimum value.
For the above tree, we start with 20, then we move left 8, we keep on moving to left until
we see NULL. Since left of 4 is NULL, 4 is the node with minimum value.
C
#include <stdio.h>
#include<stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
1150
Chapter 191. Find the node with minimum value in a Binary Search Tree
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node
with the given data and NULL left and right
pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Give a binary search tree and a number,
inserts a new node with the given number in
the correct place in the tree. Returns the new
root pointer which the caller should then use
(the standard trick to avoid using reference
parameters). */
struct node* insert(struct node* node, int data)
{
/* 1. If the tree is empty, return a new,
single node */
if (node == NULL)
return(newNode(data));
else
{
/* 2. Otherwise, recur down the tree */
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);
/* return the (unchanged) node pointer */
return node;
}
}
/* Given a non-empty binary search tree,
return the minimum data value found in that
tree. Note that the entire tree does not need
1151
Chapter 191. Find the node with minimum value in a Binary Search Tree
to be searched. */
int minValue(struct node* node) {
struct node* current = node;
/* loop down to find the leftmost leaf */
while (current->left != NULL) {
current = current->left;
}
return(current->data);
}
/* Driver program to test sameTree function*/
int main()
{
struct node* root = NULL;
root = insert(root, 4);
insert(root, 2);
insert(root, 1);
insert(root, 3);
insert(root, 6);
insert(root, 5);
printf("\n Minimum value in BST is %d", minValue(root));
getchar();
return 0;
}
Java
1152
Chapter 191. Find the node with minimum value in a Binary Search Tree
1153
Chapter 191. Find the node with minimum value in a Binary Search Tree
tree.insert(root, 5);
System.out.println("The minimum value of BST is " + tree.minvalue(root));
}
}
// This code has been contributed by Mayank Jaiswal
Python
1154
Chapter 191. Find the node with minimum value in a Binary Search Tree
def minValue(node):
current = node
# loop down to find the lefmost leaf
while(current.left is not None):
current = current.left
return current.data
# Driver program
root = None
root = insert(root,4)
insert(root,2)
insert(root,1)
insert(root,3)
insert(root,6)
insert(root,5)
print "\nMinimum value in BST is %d" %(minValue(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Time Complexity: O(n) Worst case happens for left skewed trees.
Similarly we can get the maximum value by recursively traversing the right node of a binary
search tree.
References:
http://cslibrary.stanford.edu/110/BinaryTrees.html
Source
https://www.geeksforgeeks.org/find-the-minimum-element-in-a-binary-search-tree/
1155
Chapter 192
Input :
1
/ \
2 5
/ \ \
3 4 6
Output :
1
\
2
\
3
\
4
\
5
\
6
Input :
1156
Chapter 192. Flatten a binary tree into linked list
1
/ \
3 4
/
2
\
5
Output :
1
\
3
\
4
\
2
\
5
Simple Approach: A simple solution is to use Level Order Traversal using Queue. In level
order traversal, keep track of previous node. Make current node as right child of previous
and left of previous node as NULL. This solution requires queue, but question asks to solve
without additional data structure.
Efficient Without Additional Data StructureRecursively look for the node with no
grandchildren and both left and right child in the left sub-tree. Then store node->right in
temp and make node->right=node->left. Insert temp in first node NULL on right of node
by node=node->right. Repeat until it is converted to linked list.
For Example,
1157
Chapter 192. Flatten a binary tree into linked list
struct Node {
int key;
Node *left, *right;
};
/* utility that allocates a new Node
with the given key */
Node* newNode(int key)
{
Node* node = new Node;
node->key = key;
node->left = node->right = NULL;
return (node);
}
// Function to convert binary tree into
// linked list by altering the right node
// and making left node point to NULL
void flatten(struct Node* root)
{
// base condition- return if root is NULL
// or if it is a leaf node
if (root == NULL || root->left == NULL &&
root->right == NULL) {
return;
}
// if root->left exists then we have
// to make it root->right
if (root->left != NULL) {
// move left recursively
flatten(root->left);
// store the node root->right
struct Node* tmpRight = root->right;
root->right = root->left;
root->left = NULL;
// find the position to insert
// the stored value
struct Node* t = root->right;
while (t->right != NULL) {
t = t->right;
}
// insert the stored value
t->right = tmpRight;
1158
Chapter 192. Flatten a binary tree into linked list
}
// now call the same function
// for root->right
flatten(root->right);
}
// To find the inorder traversal
void inorder(struct Node* root)
{
// base condition
if (root == NULL)
return;
inorder(root->left);
cout << root->key << " ";
inorder(root->right);
}
/* Driver program to test above functions*/
int main()
{
/* 1
/ \
2 5
/ \ \
3 4 6 */
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(3);
root->left->right = newNode(4);
root->right->right = newNode(6);
flatten(root);
cout << "The Inorder traversal after "
"flattening binary tree ";
inorder(root);
return 0;
}
Output:
1159
Chapter 192. Flatten a binary tree into linked list
Source
https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list/
1160
Chapter 193
Input:
1
/ \
2 5
/ \ \
3 4 6
Output:
1
\
2
\
3
\
4
\
5
\
6
Input:
1
1161
Chapter 193. Flatten a binary tree into linked list | Set-2
/ \
3 4
/
2
\
5
Output:
1
\
3
\
4
\
2
\
5
Approach: An approach using recursion has already been discussed in the previous post.
A pre-order traversal of the binary tree using stack has been implied in this approach. In
this traversal, every time a right child is pushed in the stack, the right child is made equal
to the left child and left child is made equal to NULL. If the right child of the node becomes
NULL, the stack is popped and the right child becomes the popped value from the stack.
The above steps are repeated until the size of the stack is zero or root is NULL.
Below is the implementation of the above approach:
1162
Chapter 193. Flatten a binary tree into linked list | Set-2
1163
Chapter 193. Flatten a binary tree into linked list | Set-2
{
/* 1
/ \
2 5
/ \ \
3 4 6 */
// Build the tree
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(3);
root->left->right = newNode(4);
root->right->right = newNode(6);
// Call the function to
// flatten the tree
root = solution(root);
cout << "The Inorder traversal after "
"flattening binary tree ";
// call the function to print
// inorder after flatenning
inorder(root);
return 0;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/flatten-a-binary-tree-into-linked-list-set-2/
1164
Chapter 194
1165
Chapter 194. Flip Binary Tree
root->left->left = root->right;
root->left->right = root;
root->left = NULL;
root->right = NULL;
as we are storing root->left in flipped root, flipped subtree gets stored in each recursive call.
C++
1166
Chapter 194. Flip Binary Tree
int data;
Node *left, *right;
};
/* Utility function to create a new Binary
Tree Node */
struct Node* newNode(int data)
{
struct Node *temp = new struct Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// method to flip the binary tree
Node* flipBinaryTree(Node* root)
{
// Base cases
if (root == NULL)
return root;
if (root->left == NULL && root->right == NULL)
return root;
// recursively call the same method
Node* flippedRoot = flipBinaryTree(root->left);
// rearranging main root Node after returning
// from recursive call
root->left->left = root->right;
root->left->right = root;
root->left = root->right = NULL;
return flippedRoot;
}
// Iterative method to do level order traversal
// line by line
void printLevelOrder(Node *root)
{
// Base Case
if (root == NULL) return;
// Create an empty queue for level order traversal
queue<Node *> q;
// Enqueue Root and initialize height
q.push(root);
1167
Chapter 194. Flip Binary Tree
while (1)
{
// nodeCount (queue size) indicates number
// of nodes at current lelvel.
int nodeCount = q.size();
if (nodeCount == 0)
break;
// Dequeue all nodes of current level and
// Enqueue all nodes of next level
while (nodeCount > 0)
{
Node *node = q.front();
cout << node->data << " ";
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
nodeCount--;
}
cout << endl;
}
}
// Driver code
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->right->left = newNode(4);
root->right->right = newNode(5);
cout << "Level order traversal of given tree\n";
printLevelOrder(root);
root = flipBinaryTree(root);
cout << "\nLevel order traversal of the flipped"
" tree\n";
printLevelOrder(root);
return 0;
}
Python
1168
Chapter 194. Flip Binary Tree
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.right = None
self.left = None
def flipBinaryTree(root):
# Base Cases
if root is None:
return root
if root.left is None and root.right is None:
return root
# Recursively call the same method
flippedRoot = flipBinaryTree(root.left)
# Rearranging main root Node after returning
# from recursive call
root.left.left = root.right
root.left.right = root
root.left = root.right = None
return flippedRoot
# Iterative method to do the level order traversal
# line by line
def printLevelOrder(root):
# Base Case
if root is None:
return
# Create an empty queue for level order traversal
from Queue import Queue
q = Queue()
# Enqueue root and initialize height
q.put(root)
while(True):
# nodeCount (queue size) indicates number
1169
Chapter 194. Flip Binary Tree
Output:
1170
Chapter 194. Flip Binary Tree
Iterative Approach
This approach is contributed by Pal13.
The iterative solution follows the same approach as the recursive one, the only thing we
need to pay attention to is to save the node information that will be overwritten.
CPP
1171
Chapter 194. Flip Binary Tree
temp = curr->right;
// Making prev as curr's right child
curr->right = prev;
prev = curr;
curr = next;
}
return prev;
}
// Iterative method to do level order traversal
// line by line
void printLevelOrder(Node *root)
{
// Base Case
if (root == NULL) return;
// Create an empty queue for level order traversal
queue<Node *> q;
// Enqueue Root and initialize height
q.push(root);
while (1)
{
// nodeCount (queue size) indicates number
// of nodes at current lelvel.
int nodeCount = q.size();
if (nodeCount == 0)
break;
// Dequeue all nodes of current level and
// Enqueue all nodes of next level
while (nodeCount > 0)
{
Node *node = q.front();
cout << node->data << " ";
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
nodeCount--;
}
cout << endl;
1172
Chapter 194. Flip Binary Tree
}
}
// Driver code
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->right->left = newNode(4);
root->right->right = newNode(5);
cout << "Level order traversal of given tree\n";
printLevelOrder(root);
root = flipBinaryTree(root);
cout << "\nLevel order traversal of the flipped"
" tree\n";
printLevelOrder(root);
return 0;
}
// This article is contributed by Pal13
Java
// Java program to flip a binary tree
import java.util.*;
class GFG
{
// A binary tree node
static class Node
{
int data;
Node left, right;
};
// Utility function to create
// a new Binary Tree Node
static Node newNode(int data)
{
Node temp = new Node();
temp.data = data;
temp.left = temp.right = null;
return temp;
}
1173
Chapter 194. Flip Binary Tree
1174
Chapter 194. Flip Binary Tree
1175
Chapter 194. Flip Binary Tree
Complexity Analysis:
Time complexity: O(n) as in the worst case, depth of binary tree will be n.
Auxiliary Space : O(1).
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/flip-binary-tree/
1176
Chapter 195
(a)
10
/ \
7 15
\ /
9 11
(b)
10
/ \
7 15
/ \
9 11
(c)
10
/ \
7 15
/ /
5 11
1177
Chapter 195. Foldable Binary Trees
(d)
10
/ \
7 15
/ \ /
9 10 12
Method 1 (Change Left subtree to its Mirror and compare it with Right subtree)
Algorithm: isFoldable(root)
#include<stdio.h>
#include<stdlib.h>
/* You would want to remove below 3 lines if your compiler
supports bool, true and false */
#define bool int
#define true 1
#define false 0
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* converts a tree to its mrror image */
void mirror(struct node* node);
1178
Chapter 195. Foldable Binary Trees
1179
Chapter 195. Foldable Binary Trees
return;
else
{
struct node* temp;
/* do the subtrees */
mirror(node->left);
mirror(node->right);
/* swap the pointers in this node */
temp = node->left;
node->left = node->right;
node->right = temp;
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test mirror() */
int main(void)
{
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->right->left = newNode(4);
root->left->right = newNode(5);
if(isFoldable(root) == 1)
{ printf("\n tree is foldable"); }
else
1180
Chapter 195. Foldable Binary Trees
Java
1181
Chapter 195. Foldable Binary Trees
}
boolean isStructSame(Node a, Node b)
{
if (a == null && b == null)
return true;
if (a != null && b != null
&& isStructSame(a.left, b.left)
&& isStructSame(a.right, b.right))
return true;
return false;
}
/* UTILITY FUNCTIONS */
/* Change a tree so that the roles of the left and
right pointers are swapped at every node.
See https://www.geeksforgeeks.org/?p=662 for details */
void mirror(Node node)
{
if (node == null)
return;
else
{
Node temp;
/* do the subtrees */
mirror(node.left);
mirror(node.right);
/* swap the pointers in this node */
temp = node.left;
node.left = node.right;
node.right = temp;
}
}
/* Driver program to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
/* The constructed binary tree is
1
/ \
2 3
\ /
1182
Chapter 195. Foldable Binary Trees
4 5
*/
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.right.left = new Node(4);
tree.root.left.right = new Node(5);
if (tree.isFoldable(tree.root))
System.out.println("tree is foldable");
else
System.out.println("Tree is not foldable");
}
}
// This code has been contributed by Mayank Jaiswal
IsFoldable(root)
1) If tree is empty then return true
2) Else check if left and right subtrees are structure wise mirrors of
each other. Use utility function IsFoldableUtil(root->left,
root->right) for this.
IsFoldableUtil(n1, n2)
1) If both trees are empty then return true.
2) If one of them is empty and other is not then return false.
3) Return true if following conditions are met
a) n1->left is mirror of n2->right
b) n1->right is mirror of n2->left
#include<stdio.h>
#include<stdlib.h>
1183
Chapter 195. Foldable Binary Trees
1184
Chapter 195. Foldable Binary Trees
/*UTILITY FUNCTIONS */
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test mirror() */
int main(void)
{
/* The constructed binary tree is
1
/ \
2 3
\ /
4 5
*/
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(5);
if(IsFoldable(root) == true)
{ printf("\n tree is foldable"); }
else
{ printf("\n tree is not foldable"); }
getchar();
return 0;
}
Java
1185
Chapter 195. Foldable Binary Trees
1186
Chapter 195. Foldable Binary Trees
1
/ \
2 3
\ /
4 5
*/
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.right.left = new Node(4);
tree.root.left.right = new Node(5);
if (tree.IsFoldable(tree.root))
System.out.println("tree is foldable");
else
System.out.println("Tree is not foldable");
}
}
// This code has been contributed by Mayank Jaiswal
Source
https://www.geeksforgeeks.org/foldable-binary-trees/
1187
Chapter 196
General Tree (Each node can have arbitrary number of children) Level Order Traversal -
GeeksforGeeks
Given a generic tree, perform a Level order traversal and print all of its nodes
Input : 10
/ / \ \
2 34 56 100
/ \ | / | \
77 88 1 7 8 9
Output : 10
2 34 56 100
77 88 1 7 8 9
Input : 1
/ / \ \
2 3 4 5
/ \ | / | \
6 7 8 9 10 11
Output : 1
2 3 4 5
6 7 8 9 10 11
The approach to this problem is similar to Level Order traversal in a binary tree. We Start
with pushing root node in a queue and for each node we pop it,print it and push all its child
in the queue.
1188
Chapter 196. General Tree (Each node can have arbitrary number of children) Level
Order Traversal
In case of a generic tree we store child nodes in a vector. Thus we put all elements of the
vector in the queue.
1189
Chapter 196. General Tree (Each node can have arbitrary number of children) Level
Order Traversal
n--;
}
cout << endl; // Print new line between two levels
}
}
// Driver program
int main()
{
/* Let us create below tree
* 10
* / / \ \
* 2 34 56 100
* / \ | / | \
* 77 88 1 7 8 9
*/
Node *root = newNode(10);
(root->child).push_back(newNode(2));
(root->child).push_back(newNode(34));
(root->child).push_back(newNode(56));
(root->child).push_back(newNode(100));
(root->child[0]->child).push_back(newNode(77));
(root->child[0]->child).push_back(newNode(88));
(root->child[2]->child).push_back(newNode(1));
(root->child[3]->child).push_back(newNode(7));
(root->child[3]->child).push_back(newNode(8));
(root->child[3]->child).push_back(newNode(9));
cout << "Level order traversal Before Mirroring\n";
LevelOrderTraversal(root);
return 0;
}
Output:
10
2 34 56 100
77 88 1 7 8 9
Source
https://www.geeksforgeeks.org/generic-tree-level-order-traversal/
1190
Chapter 197
The idea is to start from the root and level as 1. If the key matches with root’s data, return
level. Else recursively call for left and right subtrees with level as level + 1.
C
#include<stdio.h>
/* A tree node structure */
struct node
{
int data;
struct node *left;
struct node *right;
1191
Chapter 197. Get Level of a node in a Binary Tree
};
/* Helper function for getLevel(). It returns level of the data if data is
present in tree, otherwise returns 0.*/
int getLevelUtil(struct node *node, int data, int level)
{
if (node == NULL)
return 0;
if (node->data == data)
return level;
int downlevel = getLevelUtil(node->left, data, level+1);
if (downlevel != 0)
return downlevel;
downlevel = getLevelUtil(node->right, data, level+1);
return downlevel;
}
/* Returns level of given data value */
int getLevel(struct node *node, int data)
{
return getLevelUtil(node,data,1);
}
/* Utility function to create a new Binary Tree node */
struct node* newNode(int data)
{
struct node *temp = new struct node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
/* Driver function to test above functions */
int main()
{
struct node *root = new struct node;
int x;
/* Constructing tree given in the above figure */
root = newNode(3);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(1);
1192
Chapter 197. Get Level of a node in a Binary Tree
root->left->right = newNode(4);
for (x = 1; x <=5; x++)
{
int level = getLevel(root, x);
if (level)
printf(" Level of %d is %d\n", x, getLevel(root, x));
else
printf(" %d is not present in tree \n", x);
}
getchar();
return 0;
}
Java
1193
Chapter 197. Get Level of a node in a Binary Tree
return downlevel;
downlevel = getLevelUtil(node.right, data, level + 1);
return downlevel;
}
/* Returns level of given data value */
int getLevel(Node node, int data)
{
return getLevelUtil(node, data, 1);
}
/* Driver function to test above functions */
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
/* Constructing tree given in the above figure */
tree.root = new Node(3);
tree.root.left = new Node(2);
tree.root.right = new Node(5);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(4);
for (int x = 1; x <= 5; x++)
{
int level = tree.getLevel(tree.root, x);
if (level != 0)
System.out.println("Level of " + x + " is "
+ tree.getLevel(tree.root, x));
else
System.out.println(x + " is not present in tree");
}
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output:
Level of 1 is 3
Level of 2 is 2
Level of 3 is 1
Level of 4 is 3
Level of 5 is 2
Time Complexity of getLevel() is O(n) where n is the number of nodes in the given Binary
Tree.
1194
Chapter 197. Get Level of a node in a Binary Tree
Source
https://www.geeksforgeeks.org/get-level-of-a-node-in-a-binary-tree/
1195
Chapter 198
1196
Chapter 198. Get level of a node in binary tree | iterative approach
1197
Chapter 198. Get level of a node in binary tree | iterative approach
// utility function to return level of given node
int getlevel(node* root, int data)
{
queue<node*> q;
int level = 1;
q.push(root);
// extra NULL is pushed to keep track
// of all the nodes to be pushed before
// level is incremented by 1
q.push(NULL);
while (!q.empty()) {
node* temp = q.front();
q.pop();
if (temp == NULL) {
if (q.front() != NULL) {
q.push(NULL);
}
level += 1;
} else {
if (temp->data == data) {
return level;
}
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
}
}
return 0;
}
int main()
{
// create a binary tree
node* root = getnode(20);
root->left = getnode(10);
root->right = getnode(30);
root->left->left = getnode(5);
root->left->right = getnode(15);
root->left->right->left = getnode(12);
root->right->left = getnode(25);
root->right->right = getnode(40);
// return level of node
1198
Chapter 198. Get level of a node in binary tree | iterative approach
Output:
level of node 30 is 2
level of node 12 is 4
level of node 25 is 3
node 27 not found
Source
https://www.geeksforgeeks.org/get-level-node-binary-tree-iterative-approach/
1199
Chapter 199
Input :
7
/ \
6 5
/ \ / \
4 3 2 1
Output :
6
Input :
1
/ \
2 3
/ / \
4 5 6
\ / \
7 8 9
Output :
8
Traverse with inorder traversal and Apply the condition for the left node only and get
maximum of left node.
Let’s try to understand with code.
1200
Chapter 199. Get maximum left node in binary tree
1201
Chapter 199. Get maximum left node in binary tree
root->left->right = newNode(3);
root->right->left = newNode(2);
root->right->right = newNode(1);
/* 7
/ \
6 5
/ \ / \
4 3 2 1 */
cout << maxOfLeftElement(root);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/get-maximum-left-node-binary-tree/
1202
Chapter 200
Given a binary tree, how do you remove all the half nodes? - GeeksforGeeks
Given A binary Tree, how do you remove all the half nodes (which has only one child)?
Note leaves should not be touched as they have both children as NULL.
For example consider the below tree.
1203
Chapter 200. Given a binary tree, how do you remove all the half nodes?
struct node
{
int data;
struct node* left, *right;
};
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = node->right = NULL;
return(node);
}
void printInoder(struct node*root)
{
if (root != NULL)
{
printInoder(root->left);
printf("%d ",root->data);
printInoder(root->right);
}
}
// Removes all nodes with only one child and returns
// new root (note that root may change)
struct node* RemoveHalfNodes(struct node* root)
{
if (root==NULL)
return NULL;
root->left = RemoveHalfNodes(root->left);
root->right = RemoveHalfNodes(root->right);
if (root->left==NULL && root->right==NULL)
return root;
/* if current nodes is a half node with left
child NULL left, then it's right child is
returned and replaces it in the given tree */
if (root->left==NULL)
{
struct node *new_root = root->right;
free(root); // To avoid memory leak
return new_root;
}
1204
Chapter 200. Given a binary tree, how do you remove all the half nodes?
/* if current nodes is a half node with right
child NULL right, then it's right child is
returned and replaces it in the given tree */
if (root->right==NULL)
{
struct node *new_root = root->left;
free(root); // To avoid memory leak
return new_root;
}
return root;
}
// Driver program
int main(void)
{
struct node*NewRoot=NULL;
struct node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left=newNode(1);
root->left->right->right=newNode(11);
root->right->right=newNode(9);
root->right->right->left=newNode(4);
printf("Inorder traversal of given tree \n");
printInoder(root);
NewRoot = RemoveHalfNodes(root);
printf("\nInorder traversal of the modified tree \n");
printInoder(NewRoot);
return 0;
}
Java
1205
Chapter 200. Given a binary tree, how do you remove all the half nodes?
1206
Chapter 200. Given a binary tree, how do you remove all the half nodes?
return node;
}
// Driver program
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
Node NewRoot = null;
tree.root = new Node(2);
tree.root.left = new Node(7);
tree.root.right = new Node(5);
tree.root.left.right = new Node(6);
tree.root.left.right.left = new Node(1);
tree.root.left.right.right = new Node(11);
tree.root.right.right = new Node(9);
tree.root.right.right.left = new Node(4);
System.out.println("the inorder traversal of tree is ");
tree.printInorder(tree.root);
NewRoot = tree.RemoveHalfNodes(tree.root);
System.out.print("\nInorder traversal of the modified tree \n");
tree.printInorder(NewRoot);
}
}
// This code has been contributed by Mayank Jaiswal
Python
1207
Chapter 200. Given a binary tree, how do you remove all the half nodes?
# Removes all nodes with only one child and returns
# new root(note that root may change)
def RemoveHalfNodes(root):
if root is None:
return None
# Recur to left tree
root.left = RemoveHalfNodes(root.left)
# Recur to right tree
root.right = RemoveHalfNodes(root.right)
# if both left and right child is None
# the node is not a Half node
if root.left is None and root.right is None:
return root
# If current nodes is a half node with left child
# None then it's right child is returned and
# replaces it in the given tree
if root.left is None:
new_root = root.right
temp = root
root = None
del(temp)
return new_root
if root.right is None:
new_root = root.left
temp = root
root = None
del(temp)
return new_root
return root
# Driver Program
root = Node(2)
root.left = Node(7)
root.right = Node(5)
root.left.right = Node(6)
root.left.right.left = Node(1)
root.left.right.right = Node(11)
root.right.right = Node(9)
root.right.right.left = Node(4)
print "Inorder traversal of given tree"
1208
Chapter 200. Given a binary tree, how do you remove all the half nodes?
printInorder(root)
NewRoot = RemoveHalfNodes(root)
print "\nInorder traversal of the modified tree"
printInorder(NewRoot)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time complexity of the above solution is O(n) as it does a simple traversal of binary tree.
This article is contributed by Jyoti Saini. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/given-a-binary-tree-how-do-you-remove-all-the-half-nodes/
1209
Chapter 201
Algorithm:
Use a path array path[] to store current root to leaf path. Traverse from root to all leaves in
top-down fashion. While traversing, store data of all nodes in current path in array path[].
When we reach a leaf node, print the path array.
C
#include<stdio.h>
#include<stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
1210
Chapter 201. Given a binary tree, print all root-to-leaf paths
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Prototypes for funtions needed in printPaths() */
void printPathsRecur(struct node* node, int path[], int pathLen);
void printArray(int ints[], int len);
/*Given a binary tree, print out all of its root-to-leaf
paths, one per line. Uses a recursive helper to do the work.*/
void printPaths(struct node* node)
{
int path[1000];
printPathsRecur(node, path, 0);
}
/* Recursive helper function -- given a node, and an array containing
the path from the root node up to but not including this node,
print out all the root-leaf paths.*/
void printPathsRecur(struct node* node, int path[], int pathLen)
{
if (node==NULL)
return;
/* append this node to the path array */
path[pathLen] = node->data;
pathLen++;
/* it's a leaf, so print the path that led to here */
if (node->left==NULL && node->right==NULL)
{
printArray(path, pathLen);
}
else
{
/* otherwise try both subtrees */
printPathsRecur(node->left, path, pathLen);
printPathsRecur(node->right, path, pathLen);
}
}
/* UTILITY FUNCTIONS */
/* Utility that prints out an array on a line. */
void printArray(int ints[], int len)
1211
Chapter 201. Given a binary tree, print all root-to-leaf paths
{
int i;
for (i=0; i<len; i++)
{
printf("%d ", ints[i]);
}
printf("\n");
}
/* utility that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newnode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
/* Constructed binary tree is
10
/ \
8 2
/ \ /
3 5 2
*/
struct node *root = newnode(10);
root->left = newnode(8);
root->right = newnode(2);
root->left->left = newnode(3);
root->left->right = newnode(5);
root->right->left = newnode(2);
printPaths(root);
getchar();
return 0;
}
Java
1212
Chapter 201. Given a binary tree, print all root-to-leaf paths
1213
Chapter 201. Given a binary tree, print all root-to-leaf paths
Python3
"""
Python program to print all path from root to
leaf in a binary tree
"""
# binary tree node contains data field ,
# left and right pointer
class Node:
# constructor to create tree node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
1214
Chapter 201. Given a binary tree, print all root-to-leaf paths
# function to print all path from root
# to leaf in binary tree
def printPaths(root):
# list to store path
path = []
printPathsRec(root, path, 0)
# Helper function to print path from root
# to leaf in binary tree
def printPathsRec(root, path, pathLen):
# Base condition - if binary tree is
# empty return
if root is None:
return
# add current root's data into
# path_ar list
# if length of list is gre
if(len(path) > pathLen):
path[pathLen] = root.data
else:
path.append(root.data)
# increment pathLen by 1
pathLen = pathLen + 1
if root.left is None and root.right is None:
# leaf node then print the list
printArray(path, pathLen)
else:
# try for left and right subtree
printPathsRec(root.left, path, pathLen)
printPathsRec(root.right, path, pathLen)
# Helper function to print list in which
# root-to-leaf path is stored
def printArray(ints, len):
for i in ints[0 : len]:
print(i," ",end="")
print()
# Driver program to test above function
"""
Constructed binary tree is
1215
Chapter 201. Given a binary tree, print all root-to-leaf paths
10
/ \
8 2
/ \ /
3 5 2
"""
root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(5)
root.right.left = Node(2)
printPaths(root)
# This code has been contributed by Shweta Singh.
Output :
10 8 3
10 8 5
10 2 2
Source
https://www.geeksforgeeks.org/given-a-binary-tree-print-all-root-to-leaf-paths/
1216
Chapter 202
Given a binary tree, print out all of its root-to-leaf paths one per line. - GeeksforGeeks
Asked by Varun Bhatia
Here is the solution.
Algorithm:
Example:
1217
Chapter 202. Given a binary tree, print out all of its root-to-leaf paths one per line.
Example Tree
Output for the above example will be
1 2 4
1 2 5
1 3
Implementation:
C
1218
Chapter 202. Given a binary tree, print out all of its root-to-leaf paths one per line.
1219
Chapter 202. Given a binary tree, print out all of its root-to-leaf paths one per line.
}
/* Driver program to test mirror() */
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
/* Print all root-to-leaf paths of the input tree */
printPaths(root);
getchar();
return 0;
}
Java
1220
Chapter 202. Given a binary tree, print out all of its root-to-leaf paths one per line.
1221
Chapter 202. Given a binary tree, print out all of its root-to-leaf paths one per line.
Python3
Output:
1 2 4
1 2 5
1 3
1222
Chapter 202. Given a binary tree, print out all of its root-to-leaf paths one per line.
References:
http://cslibrary.stanford.edu/110/BinaryTrees.html
Improved By : Farheen Nilofer
Source
https://www.geeksforgeeks.org/given-a-binary-tree-print-out-all-of-its-root-to-leaf-paths-one-per-line/
1223
Chapter 203
Given a n-ary tree, count number of nodes which have more number of children than parents
- GeeksforGeeks
Given a N-ary tree represented as adjacency list, we need to write a program to count all
such nodes in this tree which has more number of childrens than its parent.
For Example,
In the above tree, count will be 1 as there is only one such node which is ‘2’ which has more
number of children than its parent. 2 has three children (4, 5 and 6) where as its parent, 1
1224
Chapter 203. Given a n-ary tree, count number of nodes which have more number of
children than parents
1225
Chapter 203. Given a n-ary tree, count number of nodes which have more number of
children than parents
return count;
}
// Driver program to test above functions
int main()
{
// adjacency list for n-ary tree
vector<int> adj[10];
// construct n ary tree as shown
// in above diagram
adj[1].push_back(2);
adj[1].push_back(3);
adj[2].push_back(4);
adj[2].push_back(5);
adj[2].push_back(6);
adj[3].push_back(9);
adj[5].push_back(7);
adj[5].push_back(8);
int root = 1;
cout << countNodes(adj, root);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/given-n-ary-tree-count-number-nodes-number-children-parent/
1226
Chapter 204
Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap - GeeksforGeeks
Given the level order traversal of a Complete Binary Tree, determine whether the Binary
Tree is a valid Min-Heap
Examples:
1227
Chapter 204. Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
/
67
We observe that at level 0, 30 > 22, and hence
min-heap property is not satisfied
We need to check whether each non-leaf node (parent) satisfies the heap property. For this,
we check whether each parent (at index i) is smaller than its children (at indices 2*i+1 and
2*i+2, if the parent has two children). If only one child, we only check the parent against
index 2*i+1.
C++
1228
Chapter 204. Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
Java
1229
Chapter 204. Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
System.out.println("False");
}
}
Output:
True
Source
https://www.geeksforgeeks.org/given-level-order-traversal-binary-tree-check-tree-min-heap/
1230
Chapter 205
L = (k - 1)*I + 1
Where L = Number of leaf nodes
I = Number of internal nodes
Proof:
Proof can be divided in two cases.
Case 1 (Root is Leaf):There is only one node in tree. The above formula is true for single
node as L = 1, I = 0.
Case 2 (Root is Internal Node): For trees with more than 1 nodes, root is always internal
node. The above formula can be proved using Handshaking Lemma for this case. A tree is
an undirected acyclic graph.
Total number of edges in Tree is number of nodes minus 1, i.e., |E| = L + I – 1.
1231
Chapter 205. Handshaking Lemma and Interesting Tree Properties
All internal nodes except root in the given type of tree have degree k + 1. Root has degree k.
All leaves have degree 1. Applying the Handshaking lemma to such trees, we get following
relation.
So the above property is proved using Handshaking Lemma, let us discuss one more inter-
esting property.
2) In Binary tree, number of leaf nodes is always one more than nodes with two
children.
L = T + 1
Where L = Number of leaf nodes
T = Number of internal nodes with two children
Proof:
Let number of nodes with 2 children be T. Proof can be divided in three cases.
1232
Chapter 205. Handshaking Lemma and Interesting Tree Properties
Source
https://www.geeksforgeeks.org/handshaking-lemma-and-interesting-tree-properties/
1233
Chapter 206
If you want a sorted Set then it is better to add elements to HashSet and then convert it
into TreeSet rather than creating a TreeSet and adding elements to it.
1234
Chapter 206. HashSet vs TreeSet in Java
HashSet example
Output:
HashSet contains:
practice
geeks
for
contribute
TreeSet example
1235
Chapter 206. HashSet vs TreeSet in Java
Output:
TreeSet contains:
contribute
for
geeks
practice
Source
https://www.geeksforgeeks.org/hashset-vs-treeset-in-java/
1236
Chapter 207
Input : N = 6
Output : 2
()
/ \
() ()
/ \ /
() () ()
Input : N = 9
Output :
()
/ \
() ()
/ \ / \
() () () ()
/ \
() ()
1237
Chapter 207. Height of a complete binary tree (or Heap) with N nodes
N h
---------
1 0
2 1
3 1
4 2
5 2
.....
.....
C++
Java
1238
Chapter 207. Height of a complete binary tree (or Heap) with N nodes
Python 3
C#
1239
Chapter 207. Height of a complete binary tree (or Heap) with N nodes
// This code is contributed by
// Smitha Dinesh Semwal
PHP
<?php
// PHP program to find height
// of complete binary tree
// from total nodes.
function height($N)
{
return ceil(log($N + 1, 2)) - 1;
}
// Driver Code
$N = 6;
echo height($N);
// This code is contributed by aj_36
?>
Output :
Source
https://www.geeksforgeeks.org/height-complete-binary-tree-heap-n-nodes/
1240
Chapter 208
Here, generic tree is sometimes also called as N-ary tree or N-way tree where N denotes
the maximum number of child a node can have. In this problem array represents n number
of nodes in the tree.
Approach 1:
One solution is to traverse up the tree from node till root node is reached with node value
-1. While Traversing for each node store maximum path length.
Time Complexity of this solution is O(n^2).
Approach 2:
Build graph for N-ary Tree in O(n) time and apply BFS on the stored graph in O(n) time
and while doing BFS store maximum reached level. This solution does two iterations to
find the height of N-ary tree.
1241
Chapter 208. Height of a generic tree from parent array
// tree in O(n)
#include <bits/stdc++.h>
#define MAX 1001
using namespace std;
// Adjacency list to
// store N-ary tree
vector<int> adj[MAX];
// Build tree in tree in O(n)
int build_tree(int arr[], int n)
{
int root_index = 0;
// Iterate for all nodes
for (int i = 0; i < n; i++) {
// if root node, store index
if (arr[i] == -1)
root_index = i;
else {
adj[i].push_back(arr[i]);
adj[arr[i]].push_back(i);
}
}
return root_index;
}
// Applying BFS
int BFS(int start)
{
// map is used as visited array
map<int, int> vis;
queue<pair<int, int> > q;
int max_level_reached = 0;
// height of root node is zero
q.push({ start, 0 });
// p.first denotes node in adjacency list
// p.second denotes level of p.first
pair<int, int> p;
while (!q.empty()) {
p = q.front();
1242
Chapter 208. Height of a generic tree from parent array
vis[p.first] = 1;
// store the maximum level reached
max_level_reached = max(max_level_reached,
p.second);
q.pop();
for (int i = 0; i < adj[p.first].size(); i++)
// adding 1 to previous level
// stored on node p.first
// which is parent of node adj[p.first][i]
// if adj[p.first][i] is not visited
if (!vis[adj[p.first][i]])
q.push({ adj[p.first][i], p.second + 1 });
}
return max_level_reached;
}
// Driver Function
int main()
{
// node 0 to node n-1
int parent[] = { -1, 0, 1, 2, 3 };
// Number of nodes in tree
int n = sizeof(parent) / sizeof(parent[0]);
int root_index = build_tree(parent, n);
int ma = BFS(root_index);
cout << "Height of N-ary Tree=" << ma;
return 0;
}
Output:
Time Complexity of this solution is O(2n) which converges to O(n) for very large n.
Approach 3:
We can find the height of N-ary Tree in only one iteration. We visit nodes from 0 to n-
1 iteratively and mark the unvisited ancestors recursively if they are not visited before till
we reach a node which is visited or we reach root node. If we reach visited node while
1243
Chapter 208. Height of a generic tree from parent array
traversing up the tree using parent links, then we use its height and will not go further in
recursion.
Explanation For Example 1::
1244
Chapter 208. Height of a generic tree from parent array
1245
Chapter 208. Height of a generic tree from parent array
// store maximum height so far
ma = max(ma, height[i]);
}
return ma;
}
// Driver Function
int main()
{
int parent[] = { -1, 0, 0, 0, 3, 1, 1, 2 };
int n = sizeof(parent) / sizeof(parent[0]);
cout << "Height of N-ary Tree = "
<< findHeight(parent, n);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/height-generic-tree-parent-array/
1246
Chapter 209
1247
Chapter 209. Height of binary tree considering even level leaves only
approach. In the return step, we check if the node is a valid root node or not. If it is valid,
return 1, else we return 0. Now in the recursive step- if the left and the right sub-tree both
yield 0, the current node yields 0 too, because in that case there is no path from current
node to a valid leaf node. But in case at least one of the values returned by the children is
non-zero, it means the leaf node on that path is a valid leaf node, and hence that path can
contribute to the final result, so we return max of the values returned + 1 for the current
node.
1248
Chapter 209. Height of binary tree considering even level leaves only
/*left stores the result of left subtree,
and right stores the result of right subtree*/
int left = heightOfTreeUtil(root->left, !isEven);
int right = heightOfTreeUtil(root->right, !isEven);
/*If both left and right returns 0, it means
there is no valid path till leaf node*/
if (left == 0 && right == 0)
return 0;
return (1 + max(left, right));
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
struct Node* node =
(struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
int heightOfTree(Node* root)
{
return heightOfTreeUtil(root, false);
}
/* Driver program to test above functions*/
int main()
{
// Let us create binary tree shown in above diagram
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->right->left = newNode(6);
cout << "Height of tree is " << heightOfTree(root);
return 0;
}
Output:
1249
Chapter 209. Height of binary tree considering even level leaves only
Height of tree is 4
Source
https://www.geeksforgeeks.org/height-binary-tree-considering-even-level-leaves/
1250
Chapter 210
1. Start at each node and keep going to its parent until we reach -1.
2. Also keep track of the maximum height among all nodes.
C++
1251
Chapter 210. Height of n-ary tree if parent array is given
Java
1252
Chapter 210. Height of n-ary tree if parent array is given
C#
1253
Chapter 210. Height of n-ary tree if parent array is given
Output:
Improved By : vt_m
Source
https://www.geeksforgeeks.org/height-n-ary-tree-parent-array-given/
1254
Chapter 211
1255
Chapter 211. How to determine if a binary tree is height-balanced?
To check if a tree is height-balanced, get the height of left and right subtrees. Return true
if difference between heights is not more than 1 and left and right subtrees are balanced,
otherwise return false.
C
1256
Chapter 211. How to determine if a binary tree is height-balanced?
1257
Chapter 211. How to determine if a binary tree is height-balanced?
node->left = NULL;
node->right = NULL;
return(node);
}
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->left->left = newNode(8);
if(isBalanced(root))
printf("Tree is balanced");
else
printf("Tree is not balanced");
getchar();
return 0;
}
Java
1258
Chapter 211. How to determine if a binary tree is height-balanced?
{
int lh; /* for height of left subtree */
int rh; /* for height of right subtree */
/* If tree is empty then return true */
if (node == null)
return true;
/* Get the height of left and right sub trees */
lh = height(node.left);
rh = height(node.right);
if (Math.abs(lh - rh) <= 1
&& isBalanced(node.left)
&& isBalanced(node.right))
return true;
/* If we reach here then tree is not height-balanced */
return false;
}
/* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */
/* The function Compute the "height" of a tree. Height is the
number of nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(Node node)
{
/* base case tree is empty */
if (node == null)
return 0;
/* If tree is not empty then height = 1 + max of left
height and right heights */
return 1 + Math.max(height(node.left), height(node.right));
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.left.left.left = new Node(8);
if(tree.isBalanced(tree.root))
1259
Chapter 211. How to determine if a binary tree is height-balanced?
System.out.println("Tree is balanced");
else
System.out.println("Tree is not balanced");
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Python3
"""
Python program to check if a tree is height-balanced
"""
# A binary tree Node
class Node:
# Constructor to create a new Node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# function to find height of binary tree
def height(root):
# base condition when binary tree is empty
if root is None:
return 0
return max(height(root.left), height(root.right)) + 1
# function to check if tree is height-balanced or not
def isBalanced(root):
# Base condition
if root is None:
return True
# for left and right subtree height
lh = height(root.left)
rh = height(root.right)
# allowed values for (lh - rh) are 1, -1, 0
if (abs(lh - rh) <= 1) and isBalanced(
root.left) is True and isBalanced( root.right) is True:
return True
# if we reach here means tree is not
# height-balanced tree
return False
1260
Chapter 211. How to determine if a binary tree is height-balanced?
# Driver function to test the above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.left.left.left = Node(8)
if isBalanced(root):
print("Tree is balanced")
else:
print("Tree is not balanced")
# This code is contributed by Shweta Singh
Output:
1261
Chapter 211. How to determine if a binary tree is height-balanced?
{
/* lh --> Height of left subtree
rh --> Height of right subtree */
int lh = 0, rh = 0;
/* l will be true if left subtree is balanced
and r will be true if right subtree is balanced */
int l = 0, r = 0;
if(root == NULL)
{
*height = 0;
return 1;
}
/* Get the heights of left and right subtrees in lh and rh
And store the returned values in l and r */
l = isBalanced(root->left, &lh);
r = isBalanced(root->right,&rh);
/* Height of current node is max of heights of left and
right subtrees plus 1*/
*height = (lh > rh? lh: rh) + 1;
/* If difference between heights of left and right
subtrees is more than 2 then this node is not balanced
so return 0 */
if((lh - rh >= 2) || (rh - lh >= 2))
return 0;
/* If this node is balanced and left and right subtrees
are balanced then return true */
else return l&&r;
}
/* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
1262
Chapter 211. How to determine if a binary tree is height-balanced?
return(node);
}
int main()
{
int height = 0;
/* Constructed binary tree is
1
/ \
2 3
/ \ /
4 5 6
/
7
*/
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->left->left->left = newNode(7);
if(isBalanced(root, &height))
printf("Tree is balanced");
else
printf("Tree is not balanced");
getchar();
return 0;
}
Java
1263
Chapter 211. How to determine if a binary tree is height-balanced?
}
}
// A wrapper class used to modify height across
// recursive calls.
class Height
{
int height = 0;
}
class BinaryTree {
Node root;
/* Returns true if binary tree with root as root is height-balanced */
boolean isBalanced(Node root, Height height)
{
/* If tree is empty then return true */
if (root == null)
{
height.height = 0;
return true;
}
/* Get heights of left and right sub trees */
Height lheight = new Height(), rheight = new Height();
boolean l = isBalanced(root.left, lheight);
boolean r = isBalanced(root.right, rheight);
int lh = lheight.height, rh = rheight.height;
/* Height of current node is max of heights of
left and right subtrees plus 1*/
height.height = (lh > rh? lh: rh) + 1;
/* If difference between heights of left and right
subtrees is more than 2 then this node is not balanced
so return 0 */
if ((lh - rh >= 2) ||
(rh - lh >= 2))
return false;
/* If this node is balanced and left and right subtrees
are balanced then return true */
else return l && r;
}
/* The function Compute the "height" of a tree. Height is the
1264
Chapter 211. How to determine if a binary tree is height-balanced?
number of nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(Node node)
{
/* base case tree is empty */
if (node == null)
return 0;
/* If tree is not empty then height = 1 + max of left
height and right heights */
return 1 + Math.max(height(node.left), height(node.right));
}
public static void main(String args[])
{
Height height = new Height();
/* Constructed binary tree is
1
/ \
2 3
/ \ /
4 5 6
/
7 */
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.right = new Node(6);
tree.root.left.left.left = new Node(7);
if (tree.isBalanced(tree.root, height))
System.out.println("Tree is balanced");
else
System.out.println("Tree is not balanced");
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Python3
"""
Python program to check if Binary tree is
height-balanced
1265
Chapter 211. How to determine if a binary tree is height-balanced?
"""
# A binary tree node
class Node:
# constructor to create node of
# binary tree
def __init__(self, data):
self.data = data
self.left = self.right = None
# utility class to pass height object
class Height:
def __init__(self):
self.height = 0
# helper function to check if binary
# tree is height balanced
def isBalanced(root, height):
# lh and rh to store height of
# left and right subtree
lh = Height()
rh = Height()
# Base condition when tree is
# empty return true
if root is None:
return True
# l and r are used to check if left
# and right subtree are balanced
l = isBalanced(root.left, lh)
r = isBalanced(root.right, rh)
# height of tree is maximum of
# left subtree height and
# right subtree height plus 1
height.height = max(lh.height, rh.height) + 1
if abs(lh.height - rh.height) <= 1:
return l and r
# if we reach here then the tree
# is not balanced
return False
# Driver function to test the above function
1266
Chapter 211. How to determine if a binary tree is height-balanced?
"""
Constructed binary tree is
1
/ \
2 3
/ \ /
4 5 6
/
7
"""
# to store the height of tree during traversal
height = Height()
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.left.left.left = Node(7)
if isBalanced(root, height):
print('Tree is balanced')
else:
print('Tree is not balanced')
# This code is contributed by Shweta Singh
Source
https://www.geeksforgeeks.org/how-to-determine-if-a-binary-tree-is-balanced/
1267
Chapter 212
If you are given two traversal sequences, can you construct the binary tree? - GeeksforGeeks
It depends on what traversals are given. If one of the traversal methods is Inorder then the
tree can be constructed, otherwise not.
1268
Chapter 212. If you are given two traversal sequences, can you construct the binary tree?
Preorder Traversal = AB
Postorder Traversal = BA
Level-Order Traversal = AB
So, even if three of them (Pre, Post and Level) are given, the tree can not be constructed.
Source
https://www.geeksforgeeks.org/if-you-are-given-two-traversal-sequences-can-you-construct-the-binary-tree/
1269
Chapter 213
Example :
1270
Chapter 213. Immediate Smaller element in an N-ary Tree
Explanation : Elements 2, 15, 20 and 25 are smaller than x i.e, 30, but 25 is the immediate
smaller element and hence the answer.
Approach :
1271
Chapter 213. Immediate Smaller element in an N-ary Tree
1272
Chapter 213. Immediate Smaller element in an N-ary Tree
Output :
Source
https://www.geeksforgeeks.org/immediate-smaller-element-n-ary-tree/
1273
Chapter 214
Implementation of Binary
Search Tree in Javascript
// Node class
class Node
{
constructor(data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
As in the above code snippet we define a node class having three property data, left and
right, Left and right are pointers to the left and right node in a Binary Search Tree. Data is
initialized with data which is passed when object for this node is created and left and right
is set to null.
Now lets see an example of an Binary Search Tree class.
1274
Chapter 214. Implementation of Binary Search Tree in Javascript
{
// root of a binary seach tree
this.root = null;
}
// function to be implemented
// insert(data)
// remove(data)
// Helper function
// findMinNode()
// getRootNode()
// inorder(node)
// preorder(node)
// postorder(node)
// search(node, data)
}
The above example shows a framework of a Binary Search tree class, which contains a
private variable root which holds the root of a tree, it is initialized to null.
Now lets implement each of this function:
1275
Chapter 214. Implementation of Binary Search Tree in Javascript
{
// if the data is less than the node
// data move left of the tree
if(newNode.data < node.data)
{
// if left is null insert node here
if(node.left === null)
node.left = newNode;
else
// if left is not null recurr until
// null is found
this.insertNode(node.left, newNode);
}
// if the data is more than the node
// data move right of the tree
else
{
// if right is null insert node here
if(node.right === null)
node.right = newNode;
else
// if right is not null recurr until
// null is found
this.insertNode(node.right,newNode);
}
}
In the above code we have two methods insert(data) and insertNode(node, newN-
ode). Lets understand them one by one:-
• insert(data) – It creates a new node with a value data, if the tree is empty it
add this node to tree and make it a root, otherwise it calls insert(node, data).
• insert(node, data) – It compares the given data with the data of current node
and moves left or right accordingly and recur until it finds a correct node with a
null value where new node can be added.
1276
Chapter 214. Implementation of Binary Search Tree in Javascript
}
// Method to remove node with a
// given data
// it recurrs over the tree to find the
// data and removes it
removeNode(node, key)
{
// if the root is null then tree is
// empty
if(node === null)
return null;
// if data to be delete is less than
// roots data then move to left subtree
else if(key < node.data)
{
node.left = this.removeNode(node.left, key);
return node;
}
// if data to be delete is greater than
// roots data then move to right subtree
else if(key > node.data)
{
node.right = this.removeNode(node.right, key);
return node;
}
// if data is similar to the root's data
// then delete this node
else
{
// deleting node with no children
if(node.left === null && node.right === null)
{
node = null;
return node;
}
// deleting node with one children
if(node.left === null)
{
node = node.right;
return node;
}
1277
Chapter 214. Implementation of Binary Search Tree in Javascript
While deleting a node from the tree their are three different scenarios as follows:-
• Deleting the leaf node – As leaf node do not have any children hence they can
be easily removed and null is returned to the parent node
• Deleting a node with one child – If a node have a left child then we update
the pointer of the parent node to the left child of the node to be deleted and
similarly if a node have a right child then we update the pointer of the parent
node to the right child of the node to be deleted
• Deleting a node with two children – In order to delete a node with two
children we find the node with minimum value in its right subtree and replace
this node with the minimum valued node and remove the minimum valued node
from the tree
Tree Traversal
Now Lets understand different ways of traversing a Binary Search Tree.
1278
Chapter 214. Implementation of Binary Search Tree in Javascript
Traverse the left subtree i.e perform inorder on left subtreeVisit the rootTraverse the righ
Visit the rootTraverse the left subtree i.e perform inorder on left subtreeTraverse the righ
Traverse the left subtree i.e perform inorder on left subtreeTraverse the right subtree i.e
1279
Chapter 214. Implementation of Binary Search Tree in Javascript
this.postorder(node.right);
console.log(node.data);
}
}
Helper Methods
Lets declare some helper method which are useful while working with Binary Search Tree.
As seen in the above method we start from a node and keeping moving to the left
subtree until we find a node whose left child is null, once we find such node we return
it.
2. getRootNode() – It returns the root node of a tree.
3. search(data) – It searches the node with a value data in the entire tree.
1280
Chapter 214. Implementation of Binary Search Tree in Javascript
Note : Different helper method can be declared in the BinarySearchTree class as per the
requirement.
Implementation
Now lets use the BinarySearchTree class and its different methods described above.
1281
Chapter 214. Implementation of Binary Search Tree in Javascript
// 15
// / \
// 10 25
// / \ / \
// 7 13 22 27
// \ /
// 9 17
var root = BST.getRootNode();
// prints 7 9 10 13 15 17 22 25 27
BST.inorder(root);
// Removing node with one children
BST.remove(7);
// 15
// / \
// 10 25
// / \ / \
// 9 13 22 27
// /
// 17
var root = BST.getRootNode();
// prints 9 10 13 15 17 22 25 27
BST.inorder(root);
// Removing node with two children
BST.remove(15);
// 17
// / \
// 10 25
// / \ / \
// 9 13 22 27
var root = BST.getRootNode();
console.log("inorder traversal");
// prints 9 10 13 17 22 25 27
BST.inorder(root);
1282
Chapter 214. Implementation of Binary Search Tree in Javascript
console.log("postorder traversal");
BST.postorder(root);
console.log("preorder traversal");
BST.preorder(root);
For more on binary trees please refer to the following article: Binary tree Data Structure
Source
https://www.geeksforgeeks.org/implementation-binary-search-tree-javascript/
1283
Chapter 215
In inorder traversal, we follow “left root right”. We can move to children using left and right
pointers. Once a node is visited, we need to move to parent also. For example, in the above
tree, we need to move to 10 after printing 5. For this purpose, we use parent pointer. Below
is algorithm.
1284
Chapter 215. Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
child of node.
b) Mark leftdone as true and print current node.
c) If right child of current nodes exists, set current
as right child and set leftdone as false.
d) Else If parent exists, If current node is left child
of its parent, set current node as parent.
If current node is right child, keep moving to ancestors
using parent pointer while current node is right child
of its parent.
e) Else break (We have reached back to root)
Illustration:
Below is C++ implementation of above algorithm. Note that the implementation uses
Binary Search Tree instead of Binary Tree. We can use the same function inorder() for
Binary Tree also. The reason for using Binary Search Tree in below code is, it is easy to
construct a Binary Search Tree with parent pointers and easy to test the outcome (In BST
inorder traversal is always sorted).
1285
Chapter 215. Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
C++
1286
Chapter 215. Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
1287
Chapter 215. Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
Java
1288
Chapter 215. Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
/* Otherwise, recur down the tree */
if (key < node.key)
{
node.left = insert(node.left, key);
node.left.parent = node;
}
else if (key > node.key)
{
node.right = insert(node.right, key);
node.right.parent = node;
}
/* return the (unchanged) node pointer */
return node;
}
// Function to print inorder traversal using parent
// pointer
void inorder(Node root)
{
boolean leftdone = false;
// Start traversal from root
while (root != null)
{
// If left child is not traversed, find the
// leftmost child
if (!leftdone)
{
while (root.left != null)
{
root = root.left;
}
}
// Print root's data
System.out.print(root.key + " ");
// Mark left as done
leftdone = true;
// If right child exists
if (root.right != null)
{
leftdone = false;
root = root.right;
}
1289
Chapter 215. Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
// If right child doesn't exist, move to parent
else if (root.parent != null)
{
// If this node is right child of its parent,
// visit parent's parent first
while (root.parent != null
&& root == root.parent.right)
root = root.parent;
if (root.parent == null)
break;
root = root.parent;
}
else
break;
}
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = tree.insert(tree.root, 24);
tree.root = tree.insert(tree.root, 27);
tree.root = tree.insert(tree.root, 29);
tree.root = tree.insert(tree.root, 34);
tree.root = tree.insert(tree.root, 14);
tree.root = tree.insert(tree.root, 4);
tree.root = tree.insert(tree.root, 10);
tree.root = tree.insert(tree.root, 22);
tree.root = tree.insert(tree.root, 13);
tree.root = tree.insert(tree.root, 3);
tree.root = tree.insert(tree.root, 2);
tree.root = tree.insert(tree.root, 6);
System.out.println("Inorder traversal is ");
tree.inorder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output:
Inorder traversal is
2 3 4 6 10 13 14 22 24 27 29 34
This article is contributed by Rishi Chhibber. Please write comments if you find anything
1290
Chapter 215. Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/inorder-non-threaded-binary-tree-traversal-without-recursion-or-stack/
1291
Chapter 216
1292
Chapter 216. Inorder Successor of a node in Binary Tree
1. Right child of node is not NULL. If the right child of the node is not NULL then the
inorder successor of this node will be the leftmost node in it’s right subtree.
2. Right Child of the node is NULL. If the right child of node is NULL. Then we keep
finding the parent of the given node x, say p such that p->left = x. For example in
the above given tree, inorder successor of node 5 will be 1. First parent of 5 is 2 but
2->left != 5. So next parent of 2 is 1, now 1->left = 2. Therefore, inorder successor
of 5 is 1.
Below is the algorithm for this case:
• Suppose the given node is x. Start traversing the tree from root node to find x
recursively.
• If root == x, stop recursion otherwise find x recursively for left and right sub-
trees.
• Now after finding the node x, recursion will backtrack to the root. Every recur-
sive call will return the node itself to the calling function, we will store this in a
temporary node say temp.Now, when it backtracked to its parent which will be
root now, check whether root.left = temp, if not , keep going up
3. If node is the rightmost node. If the node is the rightmost node in the given tree. For
example, in the above tree node 6 is the right most node. In this case, there will be
no inorder successor of this node. i.e. Inorder Successor of the rightmost node in a
tree is NULL.
1293
Chapter 216. Inorder Successor of a node in Binary Tree
1294
Chapter 216. Inorder Successor of a node in Binary Tree
Output:
1295
Chapter 216. Inorder Successor of a node in Binary Tree
Inorder Successor of 3 is 6
Inorder Successor of 4 is 2
No inorder successor! Right most node.
Source
https://www.geeksforgeeks.org/inorder-succesor-node-binary-tree/
1296
Chapter 217
1
/ \
2 3
/ \
4 5
Step 3 Pushes the current node and set current = current->left until current is NULL
1297
Chapter 217. Inorder Tree Traversal without Recursion
current -> 1
push 1: Stack S -> 1
current -> 2
push 2: Stack S -> 2, 1
current -> 4
push 4: Stack S -> 4, 2, 1
current = NULL
C++
1298
Chapter 217. Inorder Tree Traversal without Recursion
// using stack.
#include<bits/stdc++.h>
using namespace std;
/* A binary tree Node has data, pointer to left child
and a pointer to right child */
struct Node
{
int data;
struct Node* left;
struct Node* right;
Node (int data)
{
this->data = data;
left = right = NULL;
}
};
/* Iterative function for inorder tree
traversal */
void inOrder(struct Node *root)
{
stack<Node *> s;
Node *curr = root;
while (curr != NULL || s.empty() == false)
{
/* Reach the left most Node of the
curr Node */
while (curr != NULL)
{
/* place pointer to a tree node on
the stack before traversing
the node's left subtree */
s.push(curr);
curr = curr->left;
}
/* Current must be NULL at this point */
curr = s.top();
s.pop();
cout << curr->data << " ";
/* we have visited the node and its
left subtree. Now, it's right
subtree's turn */
curr = curr->right;
1299
Chapter 217. Inorder Tree Traversal without Recursion
} /* end of while */
}
/* Driver program to test above functions*/
int main()
{
/* Constructed binary tree is
1
/ \
2 3
/ \
4 5
*/
struct Node *root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
inOrder(root);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#define bool int
/* A binary tree tNode has data, pointer to left child
and a pointer to right child */
struct tNode
{
int data;
struct tNode* left;
struct tNode* right;
};
/* Structure of a stack node. Linked List implementation is used for
stack. A stack node contains a pointer to tree node and a pointer to
next stack node */
struct sNode
{
struct tNode *t;
struct sNode *next;
};
1300
Chapter 217. Inorder Tree Traversal without Recursion
/* Stack related functions */
void push(struct sNode** top_ref, struct tNode *t);
struct tNode *pop(struct sNode** top_ref);
bool isEmpty(struct sNode *top);
/* Iterative function for inorder tree traversal */
void inOrder(struct tNode *root)
{
/* set current to root of binary tree */
struct tNode *current = root;
struct sNode *s = NULL; /* Initialize stack s */
bool done = 0;
while (!done)
{
/* Reach the left most tNode of the current tNode */
if(current != NULL)
{
/* place pointer to a tree node on the stack before traversing
the node's left subtree */
push(&s, current);
current = current->left;
}
/* backtrack from the empty subtree and visit the tNode
at the top of the stack; however, if the stack is empty,
you are done */
else
{
if (!isEmpty(s))
{
current = pop(&s);
printf("%d ", current->data);
/* we have visited the node and its left subtree.
Now, it's right subtree's turn */
current = current->right;
}
else
done = 1;
}
} /* end of while */
}
/* UTILITY FUNCTIONS */
/* Function to push an item to sNode*/
void push(struct sNode** top_ref, struct tNode *t)
1301
Chapter 217. Inorder Tree Traversal without Recursion
{
/* allocate tNode */
struct sNode* new_tNode =
(struct sNode*) malloc(sizeof(struct sNode));
if(new_tNode == NULL)
{
printf("Stack Overflow \n");
getchar();
exit(0);
}
/* put in the data */
new_tNode->t = t;
/* link the old list off the new tNode */
new_tNode->next = (*top_ref);
/* move the head to point to the new tNode */
(*top_ref) = new_tNode;
}
/* The function returns true if stack is empty, otherwise false */
bool isEmpty(struct sNode *top)
{
return (top == NULL)? 1 : 0;
}
/* Function to pop an item from stack*/
struct tNode *pop(struct sNode** top_ref)
{
struct tNode *res;
struct sNode *top;
/*If sNode is empty then error */
if(isEmpty(*top_ref))
{
printf("Stack Underflow \n");
getchar();
exit(0);
}
else
{
top = *top_ref;
res = top->t;
*top_ref = top->next;
free(top);
return res;
1302
Chapter 217. Inorder Tree Traversal without Recursion
}
}
/* Helper function that allocates a new tNode with the
given data and NULL left and right pointers. */
struct tNode* newtNode(int data)
{
struct tNode* tNode = (struct tNode*)
malloc(sizeof(struct tNode));
tNode->data = data;
tNode->left = NULL;
tNode->right = NULL;
return(tNode);
}
/* Driver program to test above functions*/
int main()
{
/* Constructed binary tree is
1
/ \
2 3
/ \
4 5
*/
struct tNode *root = newtNode(1);
root->left = newtNode(2);
root->right = newtNode(3);
root->left->left = newtNode(4);
root->left->right = newtNode(5);
inOrder(root);
getchar();
return 0;
}
Java
1303
Chapter 217. Inorder Tree Traversal without Recursion
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
/* Class to print the inorder traversal */
class BinaryTree
{
Node root;
void inorder()
{
if (root == null)
return;
Stack<Node> s = new Stack<Node>();
Node curr = root;
// traverse the tree
while (curr != null || s.size() > 0)
{
/* Reach the left most Node of the
curr Node */
while (curr != null)
{
/* place pointer to a tree node on
the stack before traversing
the node's left subtree */
s.push(curr);
curr = curr.left;
}
/* Current must be NULL at this point */
curr = s.pop();
System.out.print(curr.data + " ");
/* we have visited the node and its
left subtree. Now, it's right
subtree's turn */
curr = curr.right;
}
1304
Chapter 217. Inorder Tree Traversal without Recursion
}
public static void main(String args[])
{
/* creating a binary tree and entering
the nodes */
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.inorder();
}
}
Python
1305
Chapter 217. Inorder Tree Traversal without Recursion
# BackTrack from the empty subtree and visit the Node
# at the top of the stack; however, if the stack is
# empty you are done
else:
if(len(s) >0 ):
current = s.pop()
print current.data,
# We have visited the node and its left
# subtree. Now, it's right subtree's turn
current = current.right
else:
done = 1
# Driver program to test above function
""" Constructed binary tree is
1
/ \
2 3
/ \
4 5 """
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
inOrder(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
4 2 5 1 3
References:
http://web.cs.wpi.edu/~cs2005/common/iterative.inorder
http://neural.cs.nthu.edu.tw/jang/courses/cs2351/slide/animation/Iterative%20Inorder%
20Traversal.pps
1306
Chapter 217. Inorder Tree Traversal without Recursion
See this post for another approach of Inorder Tree Traversal without recursion and without
stack!
Improved By : Rishabh Jindal 2
Source
https://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/
1307
Chapter 218
Although the tree is modified through the traversal, it is reverted back to its original shape
after the completion. Unlike Stack based traversal, no extra space is required for this
traversal.
C++
#include <stdio.h>
#include <stdlib.h>
/* A binary tree tNode has data, pointer to left child
and a pointer to right child */
struct tNode {
1308
Chapter 218. Inorder Tree Traversal without recursion and without stack!
int data;
struct tNode* left;
struct tNode* right;
};
/* Function to traverse binary tree without recursion and
without stack */
void MorrisTraversal(struct tNode* root)
{
struct tNode *current, *pre;
if (root == NULL)
return;
current = root;
while (current != NULL) {
if (current->left == NULL) {
printf("%d ", current->data);
current = current->right;
}
else {
/* Find the inorder predecessor of current */
pre = current->left;
while (pre->right != NULL && pre->right != current)
pre = pre->right;
/* Make current as right child of its inorder
predecessor */
if (pre->right == NULL) {
pre->right = current;
current = current->left;
}
/* Revert the changes made in if part to restore
the original tree i.e., fix the right child
of predecssor */
else {
pre->right = NULL;
printf("%d ", current->data);
current = current->right;
} /* End of if condition pre->right == NULL */
} /* End of if condition current->left == NULL*/
} /* End of while */
}
/* UTILITY FUNCTIONS */
1309
Chapter 218. Inorder Tree Traversal without recursion and without stack!
Java
1310
Chapter 218. Inorder Tree Traversal without recursion and without stack!
}
}
class BinaryTree {
tNode root;
/* Function to traverse binary tree without recursion and
without stack */
void MorrisTraversal(tNode root)
{
tNode current, pre;
if (root == null)
return;
current = root;
while (current != null) {
if (current.left == null) {
System.out.print(current.data + " ");
current = current.right;
}
else {
/* Find the inorder predecessor of current */
pre = current.left;
while (pre.right != null && pre.right != current)
pre = pre.right;
/* Make current as right child of its inorder predecessor */
if (pre.right == null) {
pre.right = current;
current = current.left;
}
/* Revert the changes made in if part to restore the
original tree i.e., fix the right child of predecssor*/
else {
pre.right = null;
System.out.print(current.data + " ");
current = current.right;
} /* End of if condition pre->right == NULL */
} /* End of if condition current->left == NULL*/
} /* End of while */
}
public static void main(String args[])
{
1311
Chapter 218. Inorder Tree Traversal without recursion and without stack!
Python
1312
Chapter 218. Inorder Tree Traversal without recursion and without stack!
Output:
4 2 5 1 3
Time Complexity : O(n) If we take a closer look, we can notice that every edge of the tree
is traversed at-most two times. And in worst case same number of extra edges (as input
tree) are created and removed.
References:
www.liacs.nl/~deutz/DS/september28.pdf
www.scss.tcd.ie/disciplines/software_systems/…/HughGibbonsSlides.pdf
1313
Chapter 218. Inorder Tree Traversal without recursion and without stack!
Source
https://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-stack/
1314
Chapter 219
struct Node
{
int key;
struct Node *left, *right ;
};
You need to find the inorder successor and predecessor of a given key. In case the given key
is not found in BST, then return the two values within which this key will lie.
Following is the algorithm to reach the desired result. Its a recursive method:
1. If root is NULL
then return
2. if key is found then
a. If its left subtree is not null
Then predecessor will be the right most
child of left subtree or left child itself.
b. If its right subtree is not null
1315
Chapter 219. Inorder predecessor and successor for a given key in BST
1316
Chapter 219. Inorder predecessor and successor for a given key in BST
while (tmp->left)
tmp = tmp->left ;
suc = tmp ;
}
return ;
}
// If key is smaller than root's key, go to left subtree
if (root->key > key)
{
suc = root ;
findPreSuc(root->left, pre, suc, key) ;
}
else // go to right subtree
{
pre = root ;
findPreSuc(root->right, pre, suc, key) ;
}
}
// A utility function to create a new BST node
Node *newNode(int item)
{
Node *temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
/* A utility function to insert a new node with given key in BST */
Node* insert(Node* node, int key)
{
if (node == NULL) return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
return node;
}
// Driver program to test above function
int main()
{
int key = 65; //Key to be searched in BST
/* Let us create following BST
50
/ \
1317
Chapter 219. Inorder predecessor and successor for a given key in BST
30 70
/ \ / \
20 40 60 80 */
Node *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
Node* pre = NULL, *suc = NULL;
findPreSuc(root, pre, suc, key);
if (pre != NULL)
cout << "Predecessor is " << pre->key << endl;
else
cout << "No Predecessor";
if (suc != NULL)
cout << "Successor is " << suc->key;
else
cout << "No Successor";
return 0;
}
Python
1318
Chapter 219. Inorder predecessor and successor for a given key in BST
# If key is present at root
if root.key == key:
# the maximum value in left subtree is predecessor
if root.left is not None:
tmp = root.left
while(tmp.right):
tmp = tmp.right
findPreSuc.pre = tmp
# the minimum value in right subtree is successor
if root.right is not None:
tmp = root.right
while(temp.left):
tmp = tmp.left
findPreSuc.suc = tmp
return
# If key is smaller than root's key, go to left subtree
if root.key > key :
findPreSuc.suc = root
findPreSuc(root.left, key)
else: # go to right subtree
findPreSuc.pre = root
findPreSuc(root.right, key)
# A utility function to insert a new node in with given key in BST
def insert(node , key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
else:
node.right = insert(node.right, key)
return node
# Driver program to test above function
key = 65 #Key to be searched in BST
""" Let us create following BST
1319
Chapter 219. Inorder predecessor and successor for a given key in BST
50
/ \
30 70
/ \ / \
20 40 60 80
"""
root = None
root = insert(root, 50)
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
# Static variables of the function findPreSuc
findPreSuc.pre = None
findPreSuc.suc = None
findPreSuc(root, key)
if findPreSuc.pre is not None:
print "Predecessor is", findPreSuc.pre.key
else:
print "No Predecessor"
if findPreSuc.suc is not None:
print "Successor is", findPreSuc.suc.key
else:
print "No Successor"
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Predecessor is 60
Successor is 70
Another Approach :
We can also find the inorder successor and inorder predecessor using inorder traversal .
Check if the current node is smaller than the given key for predecessor and for successor,
check if it is greater than the given key . If it is greater than the given key then, check if
it is smaller than the already stored value in successor then, update it . At last, get the
predecessor and successor stored in q(successor) and p(predecessor).
1320
Chapter 219. Inorder predecessor and successor for a given key in BST
1321
Chapter 219. Inorder predecessor and successor for a given key in BST
*q = root;
}
// if the root data is smaller than
// store it in p which is predecessor
else if(root && root->data < a)
{
*p = root;
}
// traverse the right subtree
find_p_s(root->right, a, p, q);
}
// Driver code
int main()
{
Node* root1 = getnode(50);
root1->left = getnode(20);
root1->right = getnode(60);
root1->left->left = getnode(10);
root1->left->right = getnode(30);
root1->right->left = getnode(55);
root1->right->right = getnode(70);
Node* p = NULL, *q = NULL;
find_p_s(root1, 55, &p, &q);
if(p)
cout << p->data;
if(q)
cout << " " << q->data;
return 0;
}
Output :
50 60
Source
https://www.geeksforgeeks.org/inorder-predecessor-successor-given-key-bst/
1322
Chapter 220
The idea is to do iterative level order traversal of the given tree using queue. If we find a
node whose left child is empty, we make new key as left child of the node. Else if we find a
node whose right child is empty, we make new key as right child. We keep traversing the
tree until we find a node whose either left or right is empty.
C++
1323
Chapter 220. Insertion in a Binary Tree
1324
Chapter 220. Insertion in a Binary Tree
} else
q.push(temp->left);
if (!temp->right) {
temp->right = newNode(key);
break;
} else
q.push(temp->right);
}
}
// Driver code
int main()
{
struct Node* root = newNode(10);
root->left = newNode(11);
root->left->left = newNode(7);
root->right = newNode(9);
root->right->left = newNode(15);
root->right->right = newNode(8);
cout << "Inorder traversal before insertion:";
inorder(root);
int key = 12;
insert(root, key);
cout << endl;
cout << "Inorder traversal after insertion:";
inorder(root);
return 0;
}
Java
1325
Chapter 220. Insertion in a Binary Tree
Node(int key){
this.key = key;
left = null;
right = null;
}
}
static Node root;
static Node temp = root;
/* Inorder traversal of a binary tree*/
static void inorder(Node temp)
{
if (temp == null)
return;
inorder(temp.left);
System.out.print(temp.key+" ");
inorder(temp.right);
}
/*function to insert element in binary tree */
static void insert(Node temp, int key)
{
Queue<Node> q = new LinkedList<Node>();
q.add(temp);
// Do level order traversal until we find
// an empty place.
while (!q.isEmpty()) {
temp = q.peek();
q.remove();
if (temp.left == null) {
temp.left = new Node(key);
break;
} else
q.add(temp.left);
if (temp.right == null) {
temp.right = new Node(key);
break;
} else
q.add(temp.right);
}
}
// Driver code
public static void main(String args[])
1326
Chapter 220. Insertion in a Binary Tree
{
root = new Node(10);
root.left = new Node(11);
root.left.left = new Node(7);
root.right = new Node(9);
root.right.left = new Node(15);
root.right.right = new Node(8);
System.out.print( "Inorder traversal before insertion:");
inorder(root);
int key = 12;
insert(root, key);
System.out.print("\nInorder traversal after insertion:");
inorder(root);
}
}
// This code is contributed by Sumit Ghosh
Output:
Source
https://www.geeksforgeeks.org/insertion-binary-tree/
1327
Chapter 221
Example Tree
Recursive method to find height of Binary Tree is discussed here. How to find height without
recursion? We can use level order traversal to find height without recursion. The idea is
to traverse level by level. Whenever move down to a level, increment height by 1 (height is
initialized as 0). Count number of nodes at each level, stop traversing when count of nodes
at next level is 0.
Following is detailed algorithm to find level order traversal using queue.
Create a queue.
1328
Chapter 221. Iterative Method to find Height of Binary Tree
1329
Chapter 221. Iterative Method to find Height of Binary Tree
int height = 0;
while (1)
{
// nodeCount (queue size) indicates number of nodes
// at current lelvel.
int nodeCount = q.size();
if (nodeCount == 0)
return height;
height++;
// Dequeue all nodes of current level and Enqueue all
// nodes of next level
while (nodeCount > 0)
{
node *node = q.front();
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
nodeCount--;
}
}
}
// Utility function to create a new tree node
node* newNode(int data)
{
node *temp = new node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in above diagram
node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Height of tree is " << treeHeight(root);
1330
Chapter 221. Iterative Method to find Height of Binary Tree
return 0;
}
Java
1331
Chapter 221. Iterative Method to find Height of Binary Tree
height++;
// Dequeue all nodes of current level and Enqueue all
// nodes of next level
while (nodeCount > 0)
{
Node newnode = q.peek();
q.remove();
if (newnode.left != null)
q.add(newnode.left);
if (newnode.right != null)
q.add(newnode.right);
nodeCount--;
}
}
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
// Let us create a binary tree shown in above diagram
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("Height of tree is " + tree.treeHeight(tree.root));
}
}
// This code has been contributed by Mayank Jaiswal
Python
1332
Chapter 221. Iterative Method to find Height of Binary Tree
def treeHeight(root):
# Base Case
if root is None:
return 0
# Create a empty queue for level order traversal
q = []
# Enqueue Root and Initialize Height
q.append(root)
height = 0
while(True):
# nodeCount(queue size) indicates number of nodes
# at current level
nodeCount = len(q)
if nodeCount == 0 :
return height
height += 1
# Dequeue all nodes of current level and Enqueue
# all nodes of next level
while(nodeCount > 0):
node = q[0]
q.pop(0)
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
nodeCount -= 1
# Driver program to test above function
# Let us create binary tree shown in above diagram
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "Height of tree is", treeHeight(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
1333
Chapter 221. Iterative Method to find Height of Binary Tree
Output:
Height of tree is 3
Source
https://www.geeksforgeeks.org/iterative-method-to-find-height-of-binary-tree/
1334
Chapter 222
1335
Chapter 222. Iterative Postorder Traversal | Set 1 (Using Two Stacks)
Following are the steps to print postorder traversal of the above tree using two stacks.
1336
Chapter 222. Iterative Postorder Traversal | Set 1 (Using Two Stacks)
The algorithm stops here since there are no more items in the first stack.
Observe that the contents of second stack are in postorder fashion. Print them.
#include <stdio.h>
#include <stdlib.h>
// Maximum stack size
#define MAX_SIZE 100
// A tree node
struct Node {
int data;
struct Node *left, *right;
};
// Stack type
struct Stack {
int size;
int top;
struct Node** array;
};
// A utility function to create a new tree node
struct Node* newNode(int data)
{
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
// A utility function to create a stack of given size
struct Stack* createStack(int size)
{
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->size = size;
stack->top = -1;
stack->array = (struct Node**)malloc(stack->size * sizeof(struct Node*));
return stack;
}
1337
Chapter 222. Iterative Postorder Traversal | Set 1 (Using Two Stacks)
// BASIC OPERATIONS OF STACK
int isFull(struct Stack* stack)
{
return stack->top - 1 == stack->size;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1;
}
void push(struct Stack* stack, struct Node* node)
{
if (isFull(stack))
return;
stack->array[++stack->top] = node;
}
struct Node* pop(struct Stack* stack)
{
if (isEmpty(stack))
return NULL;
return stack->array[stack->top--];
}
// An iterative function to do post order traversal of a given binary tree
void postOrderIterative(struct Node* root)
{
if (root == NULL)
return;
// Create two stacks
struct Stack* s1 = createStack(MAX_SIZE);
struct Stack* s2 = createStack(MAX_SIZE);
// push root to first stack
push(s1, root);
struct Node* node;
// Run while first stack is not empty
while (!isEmpty(s1)) {
// Pop an item from s1 and push it to s2
node = pop(s1);
push(s2, node);
// Push left and right children of removed item to s1
if (node->left)
1338
Chapter 222. Iterative Postorder Traversal | Set 1 (Using Two Stacks)
push(s1, node->left);
if (node->right)
push(s1, node->right);
}
// Print all elements of second stack
while (!isEmpty(s2)) {
node = pop(s2);
printf("%d ", node->data);
}
}
// Driver program to test above functions
int main()
{
// Let us construct the tree shown in above figure
struct Node* root = NULL;
root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
postOrderIterative(root);
return 0;
}
Java
1339
Chapter 222. Iterative Postorder Traversal | Set 1 (Using Two Stacks)
1340
Chapter 222. Iterative Postorder Traversal | Set 1 (Using Two Stacks)
Python
1341
Chapter 222. Iterative Postorder Traversal | Set 1 (Using Two Stacks)
# Print all elements of second stack
while s2:
node = s2.pop()
print node.data,
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
postOrderIterative(root)
Output:
4 5 2 6 7 3 1
Source
https://www.geeksforgeeks.org/iterative-postorder-traversal/
1342
Chapter 223
1343
Chapter 223. Iterative Postorder Traversal | Set 2 (Using One Stack)
Following are the steps to print postorder traversal of the above tree using one stack.
7. Current node is NULL. Pop 5 from stack. Right child of 5 doesn't exist.
Print 5. Set current node to NULL.
Stack: 3, 1, 2
1344
Chapter 223. Iterative Postorder Traversal | Set 2 (Using One Stack)
1345
Chapter 223. Iterative Postorder Traversal | Set 2 (Using One Stack)
stack->size = size;
stack->top = -1;
stack->array = (struct Node**) malloc(stack->size * sizeof(struct Node*));
return stack;
}
// BASIC OPERATIONS OF STACK
int isFull(struct Stack* stack)
{ return stack->top - 1 == stack->size; }
int isEmpty(struct Stack* stack)
{ return stack->top == -1; }
void push(struct Stack* stack, struct Node* node)
{
if (isFull(stack))
return;
stack->array[++stack->top] = node;
}
struct Node* pop(struct Stack* stack)
{
if (isEmpty(stack))
return NULL;
return stack->array[stack->top--];
}
struct Node* peek(struct Stack* stack)
{
if (isEmpty(stack))
return NULL;
return stack->array[stack->top];
}
// An iterative function to do postorder traversal of a given binary tree
void postOrderIterative(struct Node* root)
{
// Check for empty tree
if (root == NULL)
return;
struct Stack* stack = createStack(MAX_SIZE);
do
{
// Move to leftmost node
while (root)
{
// Push root's right child and then root to stack.
1346
Chapter 223. Iterative Postorder Traversal | Set 2 (Using One Stack)
if (root->right)
push(stack, root->right);
push(stack, root);
// Set root as root's left child
root = root->left;
}
// Pop an item from stack and set it as root
root = pop(stack);
// If the popped item has a right child and the right child is not
// processed yet, then make sure right child is processed before root
if (root->right && peek(stack) == root->right)
{
pop(stack); // remove right child from stack
push(stack, root); // push root back to stack
root = root->right; // change root so that the right
// child is processed next
}
else // Else print root's data and set root as NULL
{
printf("%d ", root->data);
root = NULL;
}
} while (!isEmpty(stack));
}
// Driver program to test above functions
int main()
{
// Let us construct the tree shown in above figure
struct Node* root = NULL;
root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
printf("Post order traversal of binary tree is :\n");
printf("[");
postOrderIterative(root);
printf("]");
return 0;
}
1347
Chapter 223. Iterative Postorder Traversal | Set 2 (Using One Stack)
Java
1348
Chapter 223. Iterative Postorder Traversal | Set 2 (Using One Stack)
S.push(current.right);
else
{
S.pop();
list.add(current.data);
}
/* go up the tree from left node, if the child is right
push it onto stack otherwise process parent and pop
stack */
}
else if (current.left == prev)
{
if (current.right != null)
S.push(current.right);
else
{
S.pop();
list.add(current.data);
}
/* go up the tree from right node and after coming back
from right node process parent and pop stack */
}
else if (current.right == prev)
{
S.pop();
list.add(current.data);
}
prev = current;
}
return list;
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
// Let us create trees shown in above diagram
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
1349
Chapter 223. Iterative Postorder Traversal | Set 2 (Using One Stack)
Python
1350
Chapter 223. Iterative Postorder Traversal | Set 2 (Using One Stack)
stack.append(root)
# Set root as root's left child
root = root.left
# Pop an item from stack and set it as root
root = stack.pop()
# If the popped item has a right child and the
# right child is not processed yet, then make sure
# right child is processed before root
if (root.right is not None and
peek(stack) == root.right):
stack.pop() # Remove right child from stack
stack.append(root) # Push root back to stack
root = root.right # change root so that the
# righ childis processed next
# Else print root's data and set root as None
else:
ans.append(root.data)
root = None
if (len(stack) <= 0):
break
# Driver pogram to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
print "Post Order traversal of binary tree is"
postOrderIterative(root)
print ans
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
This article is compiled byAashish Barnwal. Please write comments if you find anything
1351
Chapter 223. Iterative Postorder Traversal | Set 2 (Using One Stack)
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/iterative-postorder-traversal-using-stack/
1352
Chapter 224
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <stack>
using namespace std;
/* A binary tree node has data, left child and right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node with the given data and
1353
Chapter 224. Iterative Preorder Traversal
1354
Chapter 224. Iterative Preorder Traversal
/ \ /
3 5 2
*/
struct node *root = newNode(10);
root->left = newNode(8);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->left = newNode(2);
iterativePreorder(root);
return 0;
}
Java
1355
Chapter 224. Iterative Preorder Traversal
Python
1356
Chapter 224. Iterative Preorder Traversal
Output:
1357
Chapter 224. Iterative Preorder Traversal
10 8 3 5 2 2
This article is compiled by Saurabh Sharma and reviewed by GeeksforGeeks team. Please
write comments if you find anything incorrect, or you want to share more information about
the topic discussed above
Source
https://www.geeksforgeeks.org/iterative-preorder-traversal/
1358
Chapter 225
Output: 1 2 5 10 6 11 12 13 3 4 7 8 9
Output: 1 2 5 6 3 4 7 8 9
1359
Chapter 225. Iterative Preorder Traversal of an N-ary Tree
Preorder Traversal of an N-ary Tree is similar to the preorder traversal of Binary Search
Tree or Binary Tree with the only difference that is, all the child nodes of a parent are
traversed from left to right in a sequence.
Iterative Preorder Traversal of Binary Tree.
Cases to handle during traversal: Two Cases have been taken care of in this Iterative
Preorder Traversal Algorithm:
1. If Top of the stack is a leaf node then remove it from the stack
2. If Top of the stack is Parent with children:
• As soon as an unvisited child is found(left to right sequence), Push it to Stack
and Store it in
Auxillary List and mark the following child as visited.Then, start again from
Case-1, to explore this newly visited child.
• If all Child nodes from left to right of a Parent has been visited then remove the
Parent from
the stack.
Note: In the below python implementation, a “dequeue” is used to implement the stack
instead of a list because of its efficient append and pop operations.
Below is the implementation of the above approach:
1360
Chapter 225. Iterative Preorder Traversal of an N-ary Tree
Preorder.append(root.key)
Stack.append(root)
while len(Stack)>0:
# 'Flag' checks whether all the child
# nodes have been visited.
flag = 0
# CASE 1- If Top of the stack is a leaf
# node then remove it from the stack:
if len((Stack[len(Stack)-1]).child)== 0:
X = Stack.pop()
# CASE 2- If Top of the stack is
# Parent with children:
else:
Par = Stack[len(Stack)-1]
# a)As soon as an unvisited child is
# found(left to right sequence),
# Push it to Stack and Store it in
# Auxillary List(Marked Visited)
# Start Again from Case-1, to explore
# this newly visited child
for i in range(0, len(Par.child)):
if Par.child[i].key not in Preorder:
flag = 1
Stack.append(Par.child[i])
Preorder.append(Par.child[i].key)
break;
# b)If all Child nodes from left to right
# of a Parent have been visited
# then remove the parent from the stack.
if flag == 0:
Stack.pop()
print(Preorder)
# Execution Start From here
if __name__=='__main__':
# input nodes
'''
1
/ | \
/ | \
2 3 4
/ \ / | \
5 6 7 8 9
/ / | \
10 11 12 13
'''
1361
Chapter 225. Iterative Preorder Traversal of an N-ary Tree
root = NewNode(1)
root.child.append(NewNode(2))
root.child.append(NewNode(3))
root.child.append(NewNode(4))
root.child[0].child.append(NewNode(5))
root.child[0].child[0].child.append(NewNode(10))
root.child[0].child.append(NewNode(6))
root.child[0].child[1].child.append(NewNode(11))
root.child[0].child[1].child.append(NewNode(12))
root.child[0].child[1].child.append(NewNode(13))
root.child[2].child.append(NewNode(7))
root.child[2].child.append(NewNode(8))
root.child[2].child.append(NewNode(9))
preorderTraversal(root)
Output:
Source
https://www.geeksforgeeks.org/iterative-preorder-traversal-of-a-n-ary-tree/
1362
Chapter 226
One thing is sure that we need to traverse complete tree to decide whether key is present or
not. We can use any of the following traversals to iteratively search a key in a given binary
tree.
1) Iterative Level Order Traversal.
2) Iterative Inorder Traversal
3) Iterative Preorder Traversal
4) Iterative Postorder Traversal
Below is iterative Level Order Traversal based solution to search an item x in binary
tree.
1363
Chapter 226. Iterative Search for a key ‘x’ in Binary Tree
1364
Chapter 226. Iterative Search for a key ‘x’ in Binary Tree
q.push(node->right);
}
return false;
}
// Driver program
int main(void)
{
struct node*NewRoot=NULL;
struct node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left=newNode(1);
root->left->right->right=newNode(11);
root->right->right=newNode(9);
root->right->right->left=newNode(4);
iterativeSearch(root, 6)? cout << "Found\n": cout << "Not Found\n";
iterativeSearch(root, 12)? cout << "Found\n": cout << "Not Found\n";
return 0;
}
Output:
Found
Not Found
1365
Chapter 226. Iterative Search for a key ‘x’ in Binary Tree
{
struct node* node = new struct node;
node->data = data;
node->left = node->right = NULL;
return(node);
}
// iterative process to search an element x in a given binary tree
bool iterativeSearch(node *root, int x)
{
// Base Case
if (root == NULL)
return false;
// Create an empty stack and push root to it
stack<node *> nodeStack;
nodeStack.push(root);
// Do iterative preorder traversal to search x
while (nodeStack.empty() == false)
{
// See the top item from stack and check if it is same as x
struct node *node = nodeStack.top();
if (node->data == x)
return true;
nodeStack.pop();
// Push right and left children of the popped node to stack
if (node->right)
nodeStack.push(node->right);
if (node->left)
nodeStack.push(node->left);
}
return false;
}
// Driver program
int main(void)
{
struct node*NewRoot=NULL;
struct node *root = newNode(2);
root->left = newNode(7);
root->right = newNode(5);
root->left->right = newNode(6);
root->left->right->left=newNode(1);
root->left->right->right=newNode(11);
root->right->right=newNode(9);
1366
Chapter 226. Iterative Search for a key ‘x’ in Binary Tree
root->right->right->left=newNode(4);
iterativeSearch(root, 6)? cout << "Found\n": cout << "Not Found\n";
iterativeSearch(root, 12)? cout << "Found\n": cout << "Not Found\n";
return 0;
}
Output:
Found
Not Found
Source
https://www.geeksforgeeks.org/iterative-search-for-a-key-x-in-binary-tree/
1367
Chapter 227
Iterative Segment Tree (Range Maximum Query with Node Update) - GeeksforGeeks
Given an array arr[0 . . . n-1]. The task is to perform the following operation:
• Find the maximum of elements from index l to r where 0 <= l <= r <= n-1.
• Change value of a specified element of the array to a new value x. Given i and x,
change A[i] to x, 0 <= i <= n-1.
Examples:
We have discussed Recursive segment tree implementation. In this post, iterative implemen-
tation is discussed. The iterative version of the segment tree basically uses the fact, that for
an index i, left child = 2 * i and right child = 2 * i + 1 in the tree. The parent for an index
i in the segment tree array can be found by parent = i / 2. Thus we can easily travel up
and down through the levels of the tree one by one. At first we compute the maximum in
the ranges while constructing the tree starting from the leaf nodes and climbing up through
the levels one by one. We use the same concept while processing the queries for finding the
maximum in a range. Since there are (log n) levels in the worst case, so querying takes log
1368
Chapter 227. Iterative Segment Tree (Range Maximum Query with Node Update)
n time. For update of a particular index to a given value we start updating the segment tree
starting from the leaf nodes and update all those nodes which are affected by the updation
of the current node by gradually moving up through the levels at every iteration. Updation
also takes log n time because there we have to update all the levels starting from the leaf
node where we update the exact value at the exact index given by the user.
Below is the implementation of the above approach.
1369
Chapter 227. Iterative Segment Tree (Range Maximum Query with Node Update)
1370
Chapter 227. Iterative Segment Tree (Range Maximum Query with Node Update)
Output:
Maximum in range 1 to 5 is 28
Maximum in range 2 to 8 is 32
Source
https://www.geeksforgeeks.org/iterative-segment-tree-range-maximum-query-with-node-update/
1371
Chapter 228
The iterative version of the segment tree basically uses the fact, that for an index i, left child
= 2 * i and right child = 2 * i + 1 in the tree. The parent for an index i in the segment
tree array can be found by parent = i / 2. Thus we can easily travel up and down through
the levels of the tree one by one. At first we compute the minimum in the ranges while
constructing the tree starting from the leaf nodes and climbing up through the levels one
by one. We use the same concept while processing the queries for finding the minimum in
a range. Since there are (log n) levels in the worst case, so querying takes log n time. For
update of a particular index to a given value we start updating the segment tree starting
from the leaf nodes and update all those nodes which are affected by the updation of the
1372
Chapter 228. Iterative Segment Tree (Range Minimum Query)
current node by gradually moving up through the levels at every iteration. Updation also
takes log n time because there we have to update all the levels starting from the leaf node
where we update the exact value at the exact index given by the user.
1373
Chapter 228. Iterative Segment Tree (Range Minimum Query)
right, int n)
{
/* Basically the left and right indices will move
towards right and left respectively and with
every each next higher level and compute the
minimum at each height. */
// change the index to leaf node first
left += n;
right += n;
// initialize minimum to a very high value
int mi = (int)1e9;
while (left < right) {
// if left index in odd
if (left & 1) {
mi = min(mi, segtree[left]);
// make left index even
left++;
}
// if right index in odd
if (right & 1) {
// make right index even
right--;
mi = min(mi, segtree[right]);
}
// move to the next higher level
left /= 2;
right /= 2;
}
return mi;
}
// Driver code
int main()
{
vector<int> a = { 2, 6, 10, 4, 7, 28, 9, 11, 6, 33 };
int n = a.size();
/* Construct the segment tree by assigning
the values to the internal nodes*/
vector<int> segtree(2 * n);
1374
Chapter 228. Iterative Segment Tree (Range Minimum Query)
construct_segment_tree(segtree, a, n);
// compute minimum in the range left to right
int left = 0, right = 5;
cout << "Minimum in range " << left << " to "
<< right << " is "<< range_query(segtree, left,
right + 1, n) << "\n";
// update the value of index 3 to 1
int index = 3, value = 1;
// a[3] = 1;
// Contents of array : {2, 6, 10, 1, 7, 28, 9, 11, 6, 33}
update(segtree, index, value, n); // point update
// compute minimum in the range left to right
left = 2, right = 6;
cout << "Minimum in range " << left << " to "
<< right << " is " << range_query(segtree,
left, right + 1, n) << "\n";
return 0;
}
Output:
Minimum in range 0 to 5 is 2
Minimum in range 2 to 6 is 1
Source
https://www.geeksforgeeks.org/iterative-segment-tree-range-minimum-query/
1375
Chapter 229
Output :
Diagonal Traversal of binary tree :
8 10 14
3 6 7 13
1 4
1376
Chapter 229. Iterative diagonal traversal of binary tree
struct Node {
int data;
Node *left, *right;
};
/* Helper function that allocates a new node */
Node* newNode(int data)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Iterative function to print diagonal view
void diagonalPrint(Node* root)
{
// base case
if (root == NULL)
return;
// inbuilt queue of Treenode
queue<Node*> q;
// push root
q.push(root);
// push delimiter
q.push(NULL);
while (!q.empty()) {
Node* temp = q.front();
q.pop();
// if current is delimiter then insert another
// for next diagonal and cout nextline
if (temp == NULL) {
// if queue is empty return
if (q.empty())
return;
// output nextline
cout << endl;
// push delimiter again
q.push(NULL);
}
1377
Chapter 229. Iterative diagonal traversal of binary tree
else {
while (temp) {
cout << temp->data << " ";
// if left child is present
// push into queue
if (temp->left)
q.push(temp->left);
// current equals to right child
temp = temp->right;
}
}
}
}
// Driver Code
int main()
{
Node* root = newNode(8);
root->left = newNode(3);
root->right = newNode(10);
root->left->left = newNode(1);
root->left->right = newNode(6);
root->right->right = newNode(14);
root->right->right->left = newNode(13);
root->left->right->left = newNode(4);
root->left->right->right = newNode(7);
diagonalPrint(root);
}
Output:
8 10 14
3 6 7 13
1 4
Source
https://www.geeksforgeeks.org/iterative-diagonal-traversal-binary-tree/
1378
Chapter 230
We have discussed recursive solution here. In this article iterative solution is discussed.
The idea is to use level order traversal. We traverse both trees simultaneously and compare
the data whenever we dequeue and item from queue. Below is C++ implementation of the
idea.
1379
Chapter 230. Iterative function to check if two trees are identical
1380
Chapter 230. Iterative function to check if two trees are identical
{
q1.push(n1->right);
q2.push(n2->right);
}
else if (n1->right || n2->right)
return false;
}
return true;
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
Node *root1 = newNode(1);
root1->left = newNode(2);
root1->right = newNode(3);
root1->left->left = newNode(4);
root1->left->right = newNode(5);
Node *root2 = newNode(1);
root2->left = newNode(2);
root2->right = newNode(3);
root2->left->left = newNode(4);
root2->left->right = newNode(5);
areIdentical(root1, root2)? cout << "Yes"
: cout << "No";
return 0;
}
Output:
Yes
Time complexity of above solution is O(n + m) where m and n are number of nodes in two
trees.
1381
Chapter 230. Iterative function to check if two trees are identical
Source
https://www.geeksforgeeks.org/iterative-function-check-two-trees-identical/
1382
Chapter 231
Iterative method to check if two trees are mirror of each other - GeeksforGeeks
Given two binary tress. The problem is to check whether the two binary tress are mirrors
of each other or not.
Mirror of a Binary Tree: Mirror of a Binary Tree T is another Binary Tree M(T) with
left and right children of all non-leaf nodes interchanged.
1. Perform iterative inorder traversal of one tree and iterative reverse inorder traversal
of the other tree in parallel.
1383
Chapter 231. Iterative method to check if two trees are mirror of each other
2. During these two iterative traversals check that the corresponding nodes have the same
value or not. If not same then they are not mirrors of each other.
3. If values are same, then check whether at any point in the iterative inorder traversal
one of the root becomes null and the other is not null. If this happens then they are
not mirrors of each other. This check ensures whether they have the corresponding
mirror structures or not.
4. Otherwise, both the trees are mirror of each other.
Reverse inorder traversal is the opposite of inorder traversal. In this, the right subtree
is traversed first, then root, and then the left subtree.
1384
Chapter 231. Iterative method to check if two trees are mirror of each other
return "No";
st1.push(root1);
st2.push(root2);
root1 = root1->left;
root2 = root2->right;
}
// if at any point one root becomes null and
// the other root is not null, then they are
// not mirrors. This condition verifies that
// structures of tree are mirrors of each other.
if (!(root1 == NULL && root2 == NULL))
return "No";
if (!st1.empty() && !st2.empty())
{
root1 = st1.top();
root2 = st2.top();
st1.pop();
st2.pop();
/* we have visited the node and its left subtree.
Now, it's right subtree's turn */
root1 = root1->right;
/* we have visited the node and its right subtree.
Now, it's left subtree's turn */
root2 = root2->left;
}
// both the trees have been completely traversed
else
break;
}
// tress are mirrors of each other
return "Yes";
}
// Driver program to test above
int main()
{
// 1st binary tree formation
Node *root1 = newNode(1); /* 1 */
root1->left = newNode(3); /* / \ */
root1->right = newNode(2); /* 3 2 */
root1->right->left = newNode(5); /* / \ */
1385
Chapter 231. Iterative method to check if two trees are mirror of each other
Output:
Yes
Source
https://www.geeksforgeeks.org/iterative-method-check-two-trees-mirror/
1386
Chapter 232
Input :
1
/ \
2 7
/ \ / \
3 5 8 9
/ \ /
4 6 10
Key = 6
Output : 5 2 1
Ancestors of 6 are 5, 2 and 1.
1387
Chapter 232. Iterative method to find ancestors of a given binary tree
struct Node {
int data;
struct Node* left, *right;
};
// A utility function to create a new tree node
struct Node* newNode(int data)
{
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
// Iterative Function to print all ancestors of a
// given key
void printAncestors(struct Node* root, int key)
{
if (root == NULL)
return;
// Create a stack to hold ancestors
stack<struct Node*> st;
// Traverse the complete tree in postorder way till
// we find the key
while (1) {
// Traverse the left side. While traversing, push
// the nodes into the stack so that their right
// subtrees can be traversed later
while (root && root->data != key) {
st.push(root); // push current node
root = root->left; // move to next node
}
// If the node whose ancestors are to be printed
// is found, then break the while loop.
if (root && root->data == key)
break;
// Check if right sub-tree exists for the node at top
// If not then pop that node because we don't need
// this node any more.
if (st.top()->right == NULL) {
root = st.top();
st.pop();
1388
Chapter 232. Iterative method to find ancestors of a given binary tree
Output:
5 2 1
1389
Chapter 232. Iterative method to find ancestors of a given binary tree
Source
https://www.geeksforgeeks.org/iterative-method-to-find-ancestors-of-a-given-binary-tree/
1390
Chapter 233
Example Tree
Approach
The idea is to use Level Order Traversing
1391
Chapter 233. Iterative program to Calculate Size of a tree
import java.util.LinkedList;
import java.util.Queue;
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
public int size()
{
if (root == null)
return 0;
// Using level order Traversal .
Queue<Node> q = new LinkedList<Node>();
q.offer(root);
int count = 1;
while (!q.isEmpty())
{
Node tmp = q.poll();
// when the queue is empty:
// the poll() method returns null.
if (tmp!=null)
{
if (tmp.left!=null)
{
// Increment count
count++;
// Enqueue left child
q.offer(tmp.left);
}
if (tmp.right!=null)
{
// Increment count
1392
Chapter 233. Iterative program to Calculate Size of a tree
count++;
// Enqueue left child
q.offer(tmp.right);
}
}
}
return count;
}
public static void main(String args[])
{
/* creating a binary tree and entering
the nodes */
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("The size of binary tree" +
" is : " + tree.size());
}
}
Output:
Source
https://www.geeksforgeeks.org/write-program-calculate-size-tree-iterative/
1393
Chapter 234
Example Tree
1394
Chapter 234. Iterative program to count leaf nodes in a Binary Tree
{
// If tree is empty
if (!node)
return 0;
// Initialize empty queue.
queue<Node *> q;
// Do level order traversal starting from root
int count = 0; // Initialize count of leaves
q.push(node);
while (!q.empty())
{
struct Node *temp = q.front();
q.pop();
if (temp->left != NULL)
q.push(temp->left);
if (temp->right != NULL)
q.push(temp->right);
if (temp->left == NULL && temp->right == NULL)
count++;
}
return count;
}
/* Helper function that allocates a new Node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
/* Driver program to test above functions*/
int main()
{
/* 1
/ \
2 3
/ \
4 5
Let us create Binary Tree shown in
above example */
struct Node *root = newNode(1);
1395
Chapter 234. Iterative program to count leaf nodes in a Binary Tree
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
/* get leaf count of the above created tree */
cout << getLeafCount(root);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/iterative-program-count-leaf-nodes-binary-tree/
1396
Chapter 235
The idea to do this is to first traverse the binary tree and store the ancestor of each node
in an array of size n. For example, suppose the array is anecestor[n]. Then at index i,
ancestor[i] will store the ancestor of ith node. So, the 2nd ancestor of ith node will be
ancestor[ancestor[i]] and so on. We will use this idea to calculate the kth ancestor of the
given node. We can use level order traversal to populate this array of ancestors.
Below is the C++ implementation of above idea
1397
Chapter 235. K-th ancestor of a node in Binary Tree
// A Binary Tree Node
struct Node
{
int data;
struct Node *left, *right;
};
// fucntion to generate array of ancestors
void generateArray(Node *root, int ancestors[])
{
// There will be no ancestor of root node
ancestors[root->data] = -1;
// level order traversal to
// generate 1st ancestor
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node* temp = q.front();
q.pop();
if (temp->left)
{
ancestors[temp->left->data] = temp->data;
q.push(temp->left);
}
if (temp->right)
{
ancestors[temp->right->data] = temp->data;
q.push(temp->right);
}
}
}
// function to calculate Kth ancestor
int kthAncestor(Node *root, int n, int k, int node)
{
// create array to store 1st ancestors
int ancestors[n+1] = {0};
// generate first ancestor array
generateArray(root,ancestors);
// variable to track record of number of
1398
Chapter 235. K-th ancestor of a node in Binary Tree
Output:
1399
Chapter 235. K-th ancestor of a node in Binary Tree
Time Complexity : O( n )
Auxiliary Space : O( n )
Source
https://www.geeksforgeeks.org/kth-ancestor-node-binary-tree/
1400
Chapter 236
We have discussed a BFS based solution for this problem in our previous article. If you
observe that solution carefully, you will see that the basic approach was to first find the
node and then backtrack to the kth parent. The same thing can be done using recursive
DFS without using an extra array.
The idea of using DFS is to first find the given node in the tree, and then backtrack k times
to reach to kth ancestor, once we have reached to the kth parent, we will simply print the
node and return NULL.
Below is the C++ implementation of above idea:
1401
Chapter 236. Kth ancestor of a node in binary tree | Set 2
#include <queue>
using namespace std;
// A Binary Tree Node
struct Node
{
int data;
struct Node *left, *right;
};
// temporary node to keep track of Node returned
// from previous recursive call during backtrack
Node* temp = NULL;
// recursive function to calculate Kth ancestor
Node* kthAncestorDFS(Node *root, int node , int &k)
{
// Base case
if (!root)
return NULL;
if (root->data == node||
(temp = kthAncestorDFS(root->left,node,k)) ||
(temp = kthAncestorDFS(root->right,node,k)))
{
if (k > 0)
k--;
else if (k == 0)
{
// print the kth ancestor
cout<<"Kth ancestor is: "<<root->data;
// return NULL to stop further backtracking
return NULL;
}
// return current node to previous call
return root;
}
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
1402
Chapter 236. Kth ancestor of a node in binary tree | Set 2
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in above diagram
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
int k = 2;
int node = 5;
// print kth ancestor of given node
Node* parent = kthAncestorDFS(root,node,k);
// check if parent is not NULL, it means
// there is no Kth ancestor of the node
if (parent)
cout << "-1";
return 0;
}
Output:
Time Complexity : O(n), where n is the number of nodes in the binary tree.
Source
https://www.geeksforgeeks.org/kth-ancestor-node-binary-tree-set-2/
1403
Chapter 237
K’th Largest Element in BST when modification to BST is not allowed - GeeksforGeeks
Given a Binary Search Tree (BST) and a positive integer k, find the k’th largest element in
the Binary Search Tree.
For example, in the following BST, if k = 3, then output should be 14, and if k = 5, then
output should be 10.
We have discussed two methods in thispost. The method 1 requires O(n) time. The method
2 takes O(h) time where h is height of BST, but requires augmenting the BST (storing count
of nodes in left subtree with every node).
Can we find k’th largest element in better than O(n) time and no augmentation?
In this post, a method is discussed that takes O(h + k) time. This method doesn’t require
any change to BST.
1404
Chapter 237. K’th Largest Element in BST when modification to BST is not allowed
The idea is to do reverse inorder traversal of BST. The reverse inorder traversal traverses
all nodes in decreasing order. While doing the traversal, we keep track of count of nodes
visited so far. When the count becomes equal to k, we stop the traversal and print the key.
C++
1405
Chapter 237. K’th Largest Element in BST when modification to BST is not allowed
1406
Chapter 237. K’th Largest Element in BST when modification to BST is not allowed
int c = 0;
for (int k=1; k<=7; k++)
kthLargest(root, k);
return 0;
}
Java
1407
Chapter 237. K’th Largest Element in BST when modification to BST is not allowed
return this.root;
}
if (data == node.data) {
return node;
}
/* Otherwise, recur down the tree */
if (data < node.data) {
node.left = this.insertRec(node.left, data);
} else {
node.right = this.insertRec(node.right, data);
}
return node;
}
// class that stores the value of count
public class count {
int c = 0;
}
// utility function to find kth largest no in
// a given tree
void kthLargestUtil(Node node, int k, count C)
{
// Base cases, the second condition is important to
// avoid unnecessary recursive calls
if (node == null || C.c >= k)
return;
// Follow reverse inorder traversal so that the
// largest element is visited first
this.kthLargestUtil(node.right, k, C);
// Increment count of visited nodes
C.c++;
// If c becomes k now, then this is the k'th largest
if (C.c == k) {
System.out.println(k + "th largest element is " +
node.data);
return;
}
// Recur for left subtree
this.kthLargestUtil(node.left, k, C);
}
1408
Chapter 237. K’th Largest Element in BST when modification to BST is not allowed
Time complexity: The code first traverses down to the rightmost node which takes O(h)
time, then traverses k elements in O(k) time. Therefore overall time complexity is O(h +
k).
This article is contributed by Chirag Sharma. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
1409
Chapter 237. K’th Largest Element in BST when modification to BST is not allowed
Source
https://www.geeksforgeeks.org/kth-largest-element-in-bst-when-modification-to-bst-is-not-allowed/
1410
Chapter 238
LCA for general or n-ary trees (Sparse Matrix DP approach < O(nlogn), O(logn)>) - Geeks-
forGeeks
In previous posts, we have discussed how to calculate the Lowest Common Ancestor (LCA)
for a binary tree and a binary search tree (this, this and this). Now let’s look at a method
that can calculate LCA for any tree (not only for binary tree). We use Dynamic Program-
ming with Sparse Matrix Approach in our method. This method is very handy and fast
when you need to answer multiple queries of LCA for a tree.
1411
Chapter 238. LCA for general or n-ary trees (Sparse Matrix DP approach < O(nlogn),
O(logn)>)
Pre-requisites : –
1) DFS
2) Basic DP knowledge (This and this)
3) Range Minimum Query (Square Root Decomposition and Sparse Table)
Naive Approach:- O(n)
The naive approach for this general tree LCA calculation will be the same as the naive ap-
proach for the LCA calculation of Binary Tree (this naive approach is already well described
here.
The C++ implementation for the naive approach is given below :-
1412
Chapter 238. LCA for general or n-ary trees (Sparse Matrix DP approach < O(nlogn),
O(logn)>)
}
// This Function compares the path from root to 'a' & root
// to 'b' and returns LCA of a and b. Time Complexity : O(n)
int LCA(int a, int b)
{
// trivial case
if (a == b)
return a;
// setting root to be first element in path
path[1][0] = path[2][0] = 1;
// calculating path from root to a
bool flag = false;
dfs(1, 0, 1, 1, a, flag);
// calculating path from root to b
flag = false;
dfs(1, 0, 2, 1, b, flag);
// runs till path 1 & path 2 mathches
int i = 0;
while (path[1][i] == path[2][i])
i++;
// returns the last matching node in the paths
return path[1][i-1];
}
void addEdge(int a,int b)
{
tree[a].push_back(b);
tree[b].push_back(a);
}
// Driver code
int main()
{
int n = 8; // Number of nodes
addEdge(1,2);
addEdge(1,3);
addEdge(2,4);
addEdge(2,5);
addEdge(2,6);
addEdge(3,7);
addEdge(3,8);
1413
Chapter 238. LCA for general or n-ary trees (Sparse Matrix DP approach < O(nlogn),
O(logn)>)
Output:
LCA(4, 7) = 1
LCA(4, 6) = 2
Now , as we see the above dynamic programming code runs two nested loop that runs over
their complete range respectively.
Hence, it can be easily be inferred that its asymptotic Time Complexity is O(number of
nodes * LEVEL) ~ O(n*LEVEL) ~ O(nlogn).
Return LCA(u,v) :-
1) First Step is to bring both the nodes at the same height. As we have already pre-computed
the heights for each node. We first calculate the difference in the heights of u and v (let’s
say v >=u). Now we need the node ‘v’ to jump h nodes above. This can be easily done in
O(log h) time ( where h is the difference in the heights of u and v) as we have already stored
1414
Chapter 238. LCA for general or n-ary trees (Sparse Matrix DP approach < O(nlogn),
O(logn)>)
the 2^i parent for each node. This process is exactly same as calculating x^y in O(log y)
time. (See the code for better understanding).
2) Now both u and v nodes are at same height. Therefore now once again we will use 2^i
jumping strategy to reach the first Common Parent of u and v.
Pseudo-code:
For i-> LEVEL to 0 :
If parent[u][i] != parent[v][i] :
u = parent[u][i]
v = parent[v][i]
1415
Chapter 238. LCA for general or n-ary trees (Sparse Matrix DP approach < O(nlogn),
O(logn)>)
parent[node][i] =
parent[parent[node][i-1]][i-1];
}
}
}
// Returning the LCA of u and v
// Time complexity : O(log n)
int lca(int u, int v)
{
if (depth[v] < depth[u])
swap(u, v);
int diff = depth[v] - depth[u];
// Step 1 of the pseudocode
for (int i=0; i<level; i++)
if ((diff>>i)&1)
v = parent[v][i];
// now depth[u] == depth[v]
if (u == v)
return u;
// Step 2 of the pseudocode
for (int i=level-1; i>=0; i--)
if (parent[u][i] != parent[v][i])
{
u = parent[u][i];
v = parent[v][i];
}
return parent[u][0];
}
void addEdge(int u,int v)
{
tree[u].push_back(v);
tree[v].push_back(u);
}
// driver function
int main()
{
memset(parent,-1,sizeof(parent));
int n = 8;
addEdge(1,2);
addEdge(1,3);
1416
Chapter 238. LCA for general or n-ary trees (Sparse Matrix DP approach < O(nlogn),
O(logn)>)
addEdge(2,4);
addEdge(2,5);
addEdge(2,6);
addEdge(3,7);
addEdge(3,8);
depth[0] = 0;
// running dfs and precalculating depth
// of each node.
dfs(1,0);
// Precomputing the 2^i th ancestor for evey node
precomputeSparseMatrix(n);
// calling the LCA function
cout << "LCA(4, 7) = " << lca(4,7) << endl;
cout << "LCA(4, 6) = " << lca(4,6) << endl;
return 0;
}
Output:
LCA(4,7) = 1
LCA(4,6) = 2
Time Complexity: The time complexity for answering a single LCA query will be O(logn)
but the overall time complexity is dominated by precalculation of the 2^i th ( 0<=i<=level
) ancestors for each node. Hence, the overall asymptotic Time Complexity will be O(n*logn)
and Space Complexity will be O(nlogn), for storing the data about the ancestors of each
node.
Source
https://www.geeksforgeeks.org/lca-for-general-or-n-ary-trees-sparse-matrix-dp-approach-onlogn-ologn/
1417
Chapter 239
The first step will be to decompose the tree into a flat linear array. To do this we can apply
the Euler walk . The Euler walk will give the pre-order traversal of the graph. So we will
perform a Euler Walk on the tree and store the nodes in an array as we visit them. This
process reduces the tree data-structure to a simple linear array.
Consider the below tree and the euler walk over it :-
1418
Chapter 239. LCA for n-ary Tree | Constant Query O(1)
Now lets think in general terms : Consider any two nodes on the tree. There will be exactly
one path connecting both the nodes and the node that has the smallest depth value in the
path will be the LCA of the two given nodes.
Now take any two distinct node say u and v in the Euler walk array. Now all the elements
in the path from u to v will lie in between the index of nodes u and v in the Euler walk
array. Therefore, we just need to calculate the node with the minimum depth between the
index of node u and node v in the euler array.
For this we will maintain another array that will contain the depth of all the nodes corre-
sponding to their position in the Euler walk array so that we can Apply our RMQ algorithm
on it.
Given below is the euler walk array parallel to its depth track array.
1419
Chapter 239. LCA for n-ary Tree | Constant Query O(1)
Example :- Consider two nodes node 6 and node 7 in the euler array. To calculate the
LCA of node 6 and node 7 we look the the smallest depth value for all the nodes in between
node 6 and node 7 .
Therefore, node 1 has the smallest depth value = 0 and hence, it is the LCA for node 6
and node 7.
Implementation :-
Euler Path and Depth array are the same as described above
First Appearance Index FAI[] : The First Appearance index Array will store the index
for the first position of every node in the Euler Path array. FAI[i] = First appearance of ith
node in Euler Walk array.
The C++ Implementation for the above method is given below:-
1420
Chapter 239. LCA for n-ary Tree | Constant Query O(1)
1421
Chapter 239. LCA for n-ary Tree | Constant Query O(1)
void preprocess()
{
// memorizing powers of 2
p2[0] = 1;
for (int i=1; i<18; i++)
p2[i] = p2[i-1]*2;
// memorizing all log(n) values
int val = 1,ptr=0;
for (int i=1; i<sz; i++)
{
logn[i] = ptr-1;
if (val==i)
{
val*=2;
logn[i] = ptr;
ptr++;
}
}
}
/**
* Euler Walk ( preorder traversal)
* converting tree to linear depthArray
* Time Complexity : O(n)
* */
void dfs(int cur,int prev,int dep)
{
// marking FAI for cur node
if (FAI[cur]==-1)
FAI[cur] = ptr;
level[cur] = dep;
// pushing root to euler walk
euler.push_back(cur);
// incrementing euler walk pointer
ptr++;
for (auto x:adj[cur])
{
if (x != prev)
{
dfs(x,cur,dep+1);
// pushing cur again in backtrack
1422
Chapter 239. LCA for n-ary Tree | Constant Query O(1)
1423
Chapter 239. LCA for n-ary Tree | Constant Query O(1)
Output:
LCA(6,7) : 1
LCA(6,4) : 2
Note : We are precalculating all the required power of 2’s and also precalculating the all
the required log values to ensure constant time complexity per query. Else if we did log
calculation for every query operation our Time complexity would have not been constant.
Time Complexity: The Conversion process from LCA to RMQ is done by Euler Walk
that takes O(n) time.
Pre-processing for the sparse table in RMQ takes O(nlogn) time and answering each Query
is a Constant time process. Therefore, overall Time Complexity is O(nlogn) – preprocessing
and O(1) for each query.
Source
https://www.geeksforgeeks.org/lca-n-ary-tree-constant-query-o1/
1424
Chapter 240
Input:
5
/ \
2 4
/ \
1 3
Output: 3
The following subtree is the
maximum size BST subtree
2
/ \
1 3
Input:
50
/ \
30 60
/ \ / \
5 20 45 70
1425
Chapter 240. Largest BST in a Binary Tree | Set 2
/ \
65 80
Output: 5
The following subtree is the
maximum size BST subtree
60
/ \
45 70
/ \
65 80
We traverse tree in bottom up manner. For every traversed node, we return maximum and
minimum values in subtree rooted with it. If any node follows above properties and size of
1426
Chapter 240. Largest BST in a Binary Tree | Set 2
1427
Chapter 240. Largest BST in a Binary Tree | Set 2
ret.ans = ret.sz;
ret.isBST = true;
return ret;
}
// If whole tree is not BST, return maximum
// of left and right subtrees
ret.ans = max(l.ans, r.ans);
ret.isBST = false;
return ret;
}
/* Driver program to test above functions*/
int main()
{
/* Let us construct the following Tree
60
/ \
65 70
/
50 */
struct Node *root = newNode(60);
root->left = newNode(65);
root->right = newNode(70);
root->left->left = newNode(50);
printf(" Size of the largest BST is %d\n",
largestBSTBT(root).ans);
return 0;
}
// This code is contributed by Vivek Garg in a
// comment on below set 1.
// www.geeksforgeeks.org/find-the-largest-subtree-in-a-tree-that-is-also-a-bst/
Output:
Source
https://www.geeksforgeeks.org/largest-bst-binary-tree-set-2/
1428
Chapter 241
1429
Chapter 241. Largest Independent Set Problem | DP-26
The idea is simple, there are two possibilities for every node X, either X is a member of
the set or not a member. If X is a member, then the value of LISS(X) is 1 plus LISS of all
grandchildren. If X is not a member, then the value is sum of LISS of all children.
2) Overlapping Subproblems
Following is recursive implementation that simply follows the recursive structure mentioned
above.
1430
Chapter 241. Largest Independent Set Problem | DP-26
// A utility function to create a node
struct node* newNode( int data )
{
struct node* temp = (struct node *) malloc( sizeof(struct node) );
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us construct the tree given in the above diagram
struct node *root = newNode(20);
root->left = newNode(8);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
root->right = newNode(22);
root->right->right = newNode(25);
printf ("Size of the Largest Independent Set is %d ", LISS(root));
return 0;
}
Output:
Time complexity of the above naive recursive approach is exponential. It should be noted
that the above function computes the same subproblems again and again. For example,
LISS of node with value 50 is evaluated for node with values 10 and 20 as 50 is grandchild
of 10 and child of 20.
Since same suproblems are called again, this problem has Overlapping Subprolems prop-
erty. So LISS problem has both properties (see thisand this) of a dynamic programming
problem. Like other typical Dynamic Programming(DP) problems, recomputations of same
subproblems can be avoided by storing the solutions to subproblems and solving problems
in bottom up manner.
Following is C implementation of Dynamic Programming based solution. In the following
solution, an additional field ‘liss’ is added to tree nodes. The initial value of ‘liss’ is set as
0 for all nodes. The recursive function LISS() calculates ‘liss’ for a node only if it is not
already set.
C
1431
Chapter 241. Largest Independent Set Problem | DP-26
1432
Chapter 241. Largest Independent Set Problem | DP-26
Java
1433
Chapter 241. Largest Independent Set Problem | DP-26
1434
Chapter 241. Largest Independent Set Problem | DP-26
// This code is contributed by Rishabh Mahrsee
Output
Time Complexity: O(n) where n is the number of nodes in given Binary tree.
Following extensions to above solution can be tried as an exercise.
1) Extend the above solution for n-ary tree.
2) The above solution modifies the given tree structure by adding an additional field ‘liss’
to tree nodes. Extend the solution so that it doesn’t modify the tree structure.
3) The above solution only returns size of LIS, it doesn’t print elements of LIS. Extend the
solution to print all nodes that are part of LIS.
Source
https://www.geeksforgeeks.org/largest-independent-set-problem-dp-26/
1435
Chapter 242
1436
Chapter 242. Largest number in BST which is less than or equal to N
Input : N = 24
Output :result = 21
(searching for 24 will be like-5->12->21)
Input : N = 4
Output : result = 3
(searching for 4 will be like-5->2->3)
We follow recursive approach for solving this problem. We start searching for element from
root node. If we reach a leaf and its value is greater than N, element does not exist so return
-1. Else if node’s value is less than or equal to N and right value is NULL or greater than
N, then return the node value as it will be the answer.
Otherwise if node’s value is greater than N, then search for the element in the left subtree
else search for the element in the right subtree by calling the same function by passing the
left or right values accordingly.
1437
Chapter 242. Largest number in BST which is less than or equal to N
// return the (unchanged) node pointer
return node;
}
// function to find max value less then N
int findMaxforN(Node* root, int N)
{
// Base cases
if (root == NULL)
return -1;
if (root->key == N)
return N;
// If root's value is smaller, try in rght
// subtree
else if (root->key < N) {
int k = findMaxforN(root->right, N);
if (k == -1)
return root->key;
else
return k;
}
// If root's key is greater, return value
// from left subtree.
else if (root->key > N)
return findMaxforN(root->left, N);
}
// Driver code
int main()
{
int N = 4;
// creating following BST
/*
5
/ \
2 12
/ \ / \
1 3 9 21
/ \
19 25 */
Node* root = insert(root, 25);
insert(root, 2);
insert(root, 1);
insert(root, 3);
1438
Chapter 242. Largest number in BST which is less than or equal to N
insert(root, 12);
insert(root, 9);
insert(root, 21);
insert(root, 19);
insert(root, 25);
printf("%d", findMaxforN(root, N));
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/largest-number-bst-less-equal-n/
1439
Chapter 243
Input :
1
/ \
2 3
Output : 1 3
Input :
4
/ \
9 2
/ \ \
3 5 7
Output : 4 9 7
Approach : The idea is to recursively traverse tree in a pre-order fashion. Root is con-
sidered to be at zeroth level. While traversing, keep track of the level of the element and
if its current level is not equal to the number of elements present in the list, update the
maximum element at that level in the list.
Below is the implementation to find largest value on each level of Binary Tree.
1440
Chapter 243. Largest value in each level of Binary Tree
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has data,
pointer to left child and a
pointer to right child */
struct Node {
int val;
struct Node *left, *right;
};
/* Recursive function to find
the largest value on each level */
void helper(vector<int>& res, Node* root, int d)
{
if (!root)
return;
// Expand list size
if (d == res.size())
res.push_back(root->val);
else
// to ensure largest value
// on level is being stored
res[d] = max(res[d], root->val);
// Recursively traverse left and
// right subtrees in order to find
// out the largest value on each level
helper(res, root->left, d + 1);
helper(res, root->right, d + 1);
}
// function to find largest values
vector<int> largestValues(Node* root)
{
vector<int> res;
helper(res, root, 0);
return res;
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node* newNode(int data)
{
1441
Chapter 243. Largest value in each level of Binary Tree
Output:
4 9 7
Source
https://www.geeksforgeeks.org/largest-value-level-binary-tree/
1442
Chapter 244
Largest value in each level of Binary Tree | Set-2 (Iterative Approach) - GeeksforGeeks
Given a binary tree containing n nodes. The problem is to find and print the largest value
present in each level.
Examples:
Input :
1
/ \
2 3
Output : 1 3
Input :
4
/ \
9 2
/ \ \
3 5 7
Output : 4 9 7
Approach: In the previous post, a recursive method have been discussed. In this post an
iterative method has been discussed. The idea is to perform iterative level order traversal of
the binary tree using queue. While traversing keep max variable which stores the maximum
element of the current level of the tree being processed. When the level is completely
traversed, print that max value.
1443
Chapter 244. Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
1444
Chapter 244. Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
// level
max = INT_MIN;
while (nc--) {
// get the front element from 'q'
Node* front = q.front();
// remove front element from 'q'
q.pop();
// if true, then update 'max'
if (max < front->data)
max = front->data;
// if left child exists
if (front->left)
q.push(front->left);
// if right child exists
if (front->right)
q.push(front->right);
}
// print maximum element of
// current level
cout << max << " ";
}
}
// Driver program to test above
int main()
{
/* Construct a Binary Tree
4
/ \
9 2
/ \ \
3 5 7 */
Node* root = NULL;
root = newNode(4);
root->left = newNode(9);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->right = newNode(7);
1445
Chapter 244. Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
largestValueInEachLevel(root);
return 0;
}
Output:
4 9 7
Source
https://www.geeksforgeeks.org/largest-value-level-binary-tree-set-2-iterative-approach/
1446
Chapter 245
Leaf nodes from Preorder of a Binary Search Tree (Using Recursion) - GeeksforGeeks
Given Preorder traversal of a Binary Search Tree. Then the task is print leaf nodes of the
Binary Search Tree from the given preorder.
Examples :
Input : preorder[] = { 3, 2, 4 };
Output : 2 4
In this post, a simple recursive solution is discussed. The idea is to use two min and
max variables and taking i (index in input array), the index for given preorder array, and
recursively creating root node and correspondingly checking if left and right are existing
or not. This method return boolean variable, and if both left and right are false it simply
means that left and right are null hence it must be a leaf node so print it right there and
return back true as root at that index existed.
1447
Chapter 245. Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
C++
PHP
<?php
1448
Chapter 245. Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
Output :
1449
Chapter 245. Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
Improved By : jit_t
Source
https://www.geeksforgeeks.org/leaf-nodes-preorder-binary-search-treeusing-recursion/
1450
Chapter 246
Left-Child Right-Sibling
Representation of Tree
A typical representation of n-ary tree uses an array of n references (or pointers) to store
children (Note that n is an upper bound on number of children). Can we do better? the
idea of Left-Child Right- Sibling representation is to store only two pointers in every node.
Left-Child Right Sibling Representation
It is a different representation of an n-ary tree where instead of holding a reference to each
and every child node, a node holds just two references, first a reference to it’s first child,
and the other to it’s immediate next sibling. This new transformation not only removes the
need of advance knowledge of the number of children a node has, but also limits the number
of references to a maximum of two, thereby making it so much easier to code. One thing
to note is that in the previous representation a link between two nodes denoted a parent-
child relationship whereas in this representation a link between two nodes may denote a
parent-child relationship or a sibling-sibling relationship.
Advantages :
1. This representation saves up memory by limiting the maximum number of references
required per node to two.
2. It is easier to code.
Disadvantages :
1. Basic operations like searching/insertion/deletion tend to take a longer time because in
1451
Chapter 246. Left-Child Right-Sibling Representation of Tree
order to find the appropriate position we would have to traverse through all the siblings of
the node to be searched/inserted/deleted (in the worst case).
The image on the left is the normal representation of a 6-ary tree and the one on the right
is it’s corresponding Left-Child Right-Sibling representation.
1452
Chapter 246. Left-Child Right-Sibling Representation of Tree
Input : A 2
Output : C
In this case, the user wishes to know A's
second child which according to the figure
is C.
Input : F 3
Output : K
Similar to the first case, the user wishes
to know F's third child which is K.
1453
Chapter 246. Left-Child Right-Sibling Representation of Tree
1454
Chapter 246. Left-Child Right-Sibling Representation of Tree
Output:
In the above tree, had there been a node which had say, 15 children, then this code would
have given a Segmentation fault.
Method 2 : (Left-Child Right-Sibling Representation)
In this method, we change the structure of the family tree. In the standard tree, each parent
node is connected to all of its children. Here as discussed above, instead of having each node
store pointers to all of its children, a node will store pointer to just one of its child. Apart
from this the node will also store a pointer to its immediate right sibling.
The image below is the Left-Child Right-Sibling equivalent of the example used above.
1455
Chapter 246. Left-Child Right-Sibling Representation of Tree
1456
Chapter 246. Left-Child Right-Sibling Representation of Tree
printKthChild(root->child, P, k);
printKthChild(root->next, P, k);
}
// Driver code
int main()
{
Node *root = new Node('A');
root->child = new Node('B');
root->child->next = new Node('C');
root->child->next->next = new Node('D');
root->child->next->next->next = new Node('E');
root->child->child = new Node('F');
root->child->child->next = new Node('G');
root->child->next->next->child = new Node('H');
root->child->next->next->child->child = new Node('L');
root->child->next->next->child->child->next = new Node('M');
root->child->child->child = new Node('I');
root->child->child->child->next = new Node('J');
root->child->child->child->next->next = new Node('K');
// Print F's 2nd child
char P = 'F';
cout << "F's second child is : ";
printKthChild(root, P, 2);
P = 'A';
cout << "A's seventh child is : ";
printKthChild(root, P, 7);
return 0;
}
Output:
Related Article :
Creating a tree with Left-Child Right-Sibling Representation
Source
https://www.geeksforgeeks.org/left-child-right-sibling-representation-tree/
1457
Chapter 247
Example: The below leftist tree is presented with its distance calculated for each node with
the procedure mentioned above. The rightmost node has a rank of 0 as the right subtree of
this node is null and its parent has a distance of 1 by dist( i ) = 1 + dist( right( i )). The
same is followed for each node and their s-value( or rank) is calculated.
1458
Chapter 247. Leftist Tree / Leftist Heap
1. The path from root to rightmost leaf is the shortest path from root to a leaf.
2. If the path to rightmost leaf has x nodes, then leftist heap has atleast 2x – 1 nodes.
This means the length of path to rightmost leaf is O(log n) for a leftist heap with n
nodes.
Operations :
Source : http://courses.cs.washington.edu/courses/cse326/08sp/lectures/05-leftist-heaps.
pdf
Detailed Steps for Merge:
1459
Chapter 247. Leftist Tree / Leftist Heap
2. Push the smaller key into an empty stack, and move to the right child of smaller key.
3. Recursively compare two keys and go on pushing the smaller key onto the stack and
move to its right child.
4. Repeat until a null node is reached.
5. Take the last node processed and make it the right child of the node at top of the
stack, and convert it to leftist heap if the properties of leftist heap are violated.
6. Recursively go on popping the elements from the stack and making them the right
child of new stack top.
Example:
Consider two leftist heaps given below:
The subtree at node 7 violates the property of leftist heap so we swap it with the left child
1460
Chapter 247. Leftist Tree / Leftist Heap
1461
Chapter 247. Leftist Tree / Leftist Heap
The worst case time complexity of this algorithm is O(log n) in the worst case, where n is
the number of nodes in the leftist heap.
Another example of merging two leftist heap:
1462
Chapter 247. Leftist Tree / Leftist Heap
1463
Chapter 247. Leftist Tree / Leftist Heap
this->element = element;
right = rt;
left = lt,
dist = np;
}
};
//Class Declaration
class LeftistHeap
{
public:
LeftistHeap();
LeftistHeap(LeftistHeap &rhs);
~LeftistHeap();
bool isEmpty();
bool isFull();
int &findMin();
void Insert(int &x);
void deleteMin();
void deleteMin(int &minItem);
void makeEmpty();
void Merge(LeftistHeap &rhs);
LeftistHeap & operator =(LeftistHeap &rhs);
private:
LeftistNode *root;
LeftistNode *Merge(LeftistNode *h1,
LeftistNode *h2);
LeftistNode *Merge1(LeftistNode *h1,
LeftistNode *h2);
void swapChildren(LeftistNode * t);
void reclaimMemory(LeftistNode * t);
LeftistNode *clone(LeftistNode *t);
};
// Construct the leftist heap
LeftistHeap::LeftistHeap()
{
root = NULL;
}
// Copy constructor.
LeftistHeap::LeftistHeap(LeftistHeap &rhs)
{
root = NULL;
*this = rhs;
}
// Destruct the leftist heap
1464
Chapter 247. Leftist Tree / Leftist Heap
LeftistHeap::~LeftistHeap()
{
makeEmpty( );
}
/* Merge rhs into the priority queue.
rhs becomes empty. rhs must be different
from this.*/
void LeftistHeap::Merge(LeftistHeap &rhs)
{
if (this == &rhs)
return;
root = Merge(root, rhs.root);
rhs.root = NULL;
}
/* Internal method to merge two roots.
Deals with deviant cases and calls recursive Merge1.*/
LeftistNode *LeftistHeap::Merge(LeftistNode * h1,
LeftistNode * h2)
{
if (h1 == NULL)
return h2;
if (h2 == NULL)
return h1;
if (h1->element < h2->element)
return Merge1(h1, h2);
else
return Merge1(h2, h1);
}
/* Internal method to merge two roots.
Assumes trees are not empty, and h1's root contains
smallest item.*/
LeftistNode *LeftistHeap::Merge1(LeftistNode * h1,
LeftistNode * h2)
{
if (h1->left == NULL)
h1->left = h2;
else
{
h1->right = Merge(h1->right, h2);
if (h1->left->dist < h1->right->dist)
swapChildren(h1);
h1->dist = h1->right->dist + 1;
}
return h1;
}
1465
Chapter 247. Leftist Tree / Leftist Heap
// Swaps t's two children.
void LeftistHeap::swapChildren(LeftistNode * t)
{
LeftistNode *tmp = t->left;
t->left = t->right;
t->right = tmp;
}
/* Insert item x into the priority queue, maintaining
heap order.*/
void LeftistHeap::Insert(int &x)
{
root = Merge(new LeftistNode(x), root);
}
/* Find the smallest item in the priority queue.
Return the smallest item, or throw Underflow if empty.*/
int &LeftistHeap::findMin()
{
return root->element;
}
/* Remove the smallest item from the priority queue.
Throws Underflow if empty.*/
void LeftistHeap::deleteMin()
{
LeftistNode *oldRoot = root;
root = Merge(root->left, root->right);
delete oldRoot;
}
/* Remove the smallest item from the priority queue.
Pass back the smallest item, or throw Underflow if empty.*/
void LeftistHeap::deleteMin(int &minItem)
{
if (isEmpty())
{
cout<<"Heap is Empty"<<endl;
return;
}
minItem = findMin();
deleteMin();
}
/* Test if the priority queue is logically empty.
Returns true if empty, false otherwise*/
bool LeftistHeap::isEmpty()
1466
Chapter 247. Leftist Tree / Leftist Heap
{
return root == NULL;
}
/* Test if the priority queue is logically full.
Returns false in this implementation.*/
bool LeftistHeap::isFull()
{
return false;
}
// Make the priority queue logically empty
void LeftistHeap::makeEmpty()
{
reclaimMemory(root);
root = NULL;
}
// Deep copy
LeftistHeap &LeftistHeap::operator =(LeftistHeap & rhs)
{
if (this != &rhs)
{
makeEmpty();
root = clone(rhs.root);
}
return *this;
}
// Internal method to make the tree empty.
void LeftistHeap::reclaimMemory(LeftistNode * t)
{
if (t != NULL)
{
reclaimMemory(t->left);
reclaimMemory(t->right);
delete t;
}
}
// Internal method to clone subtree.
LeftistNode *LeftistHeap::clone(LeftistNode * t)
{
if (t == NULL)
return NULL;
else
return new LeftistNode(t->element, clone(t->left),
clone(t->right), t->dist);
1467
Chapter 247. Leftist Tree / Leftist Heap
}
//Driver program
int main()
{
LeftistHeap h;
LeftistHeap h1;
LeftistHeap h2;
int x;
int arr[]= {1, 5, 7, 10, 15};
int arr1[]= {22, 75};
h.Insert(arr[0]);
h.Insert(arr[1]);
h.Insert(arr[2]);
h.Insert(arr[3]);
h.Insert(arr[4]);
h1.Insert(arr1[0]);
h1.Insert(arr1[1]);
h.deleteMin(x);
cout<< x <<endl;
h1.deleteMin(x);
cout<< x <<endl;
h.Merge(h1);
h2 = h;
h2.deleteMin(x);
cout<< x << endl;
return 0;
}
Output:
1
22
5
References:
Wikipedia- Leftist Tree
CSC378: Leftist Trees
1468
Chapter 247. Leftist Tree / Leftist Heap
Source
https://www.geeksforgeeks.org/leftist-tree-leftist-heap/
1469
Chapter 248
1470
Chapter 248. Level Ancestor Problem
Below is the algorithm to fill the ancestor matrix and depth of each node using dynamic
programming. Here, we denote root node as R and initially assume the ancestor of root
node as 0. We also initialize depth array with -1 means the depth of the current node is
not set and we need to find its depth. If the depth of the current node is not equal to -1
means we have already computed its depth.
In the given figure we need to compute 1st level ancestor of the node with value 8. First,
we make ancestor matrix which stores 2ith ancestor of nodes. Now, 20 ancestor of node 8
is 10 and similarly 20 ancestor of node 10 is 9 and for node 9 it is 1 and for node 1 it is 5.
Based on the above algorithm 1st level ancestor of node 8 is( depth(8)-1 )th ancestor of
node 8. We have pre computed depth of each node and depth of 8 is 5 so we finally need to
1471
Chapter 248. Level Ancestor Problem
find (5-1) = 4th ancestor of node 8 which is equal to 21 th ancestor of [21 ancestor of
node 8] and 21 th ancestor of node 8 is 20 th ancestor of [20 th ancestor of node 8].
So, 20 th ancestor of [20 th ancestor of node 8] is node with value 9 and 21 th ancestor
of node 9 is node with value 5. Thus in this way we can compute all query in O(logn) time
complexity.
1472
Chapter 248. Level Ancestor Problem
// if ancestor of current node is 0 means it
// does not have root node at its 2th power
// on its path so its depth is 2^(index of
// last non zero ancestor means j-1) + depth
// of 2^(j-1) th ancestor
else if (ancstr[node[i]][j] == 0 &&
node[i] != R && depth[node[i]] == -1) {
depth[node[i]] = pow(2, j - 1) +
depth[ancstr[node[i]][j - 1]];
}
}
}
}
// c -> it represent child
// p -> it represent ancestor
// i -> it represent node number
// p=0 means the node is root node
// R represent root node
// here also we pass reference of 2D matrix and depth
// vector so that the change made occur directly to
// the original matrix and original vector
void constructGraph(vector<vector<int> >& ancstr,
int* node, vector<int>& depth, int* isNode,
int c, int p, int i)
{
// enter the node in node array
// it stores all the nodes in the graph
node[i] = c;
// to confirm that no child node have 2 ancestors
if (isNode == 0) {
isNode = 1;
// make ancestor of x as y
ancstr[0] = p;
// ifits first ancestor is root than its depth is 1
if (R == p) {
depth = 1;
}
}
return;
}
// this function will delete leaf node
// x is node to be deleted
1473
Chapter 248. Level Ancestor Problem
1474
Chapter 248. Level Ancestor Problem
j++;
}
return;
}
// LA function to find Lth level ancestor of node x
void LA(vector<vector<int> >& ancstr, vector<int> depth,
int* isNode, int x, int L)
{
int j = 0;
int temp = x;
// to check if node is present in graph or not
if (isNode[x] == 0) {
cout << "Node is not present in graph " << endl;
return;
}
// we change L as depth of node x -
int k = depth[x] - L;
// int q = k;
// in this loop we decrease the value of k by k/2 and
// increment j by 1 after each iteration, and check for set bit
// if we get set bit then we update x with jth ancestor of x
// as k becomes less than or equal to zero means we
// reach to kth level ancestor
while (k > 0) {
// to check if last bit is 1 or not
if (k & 1) {
x = ancstr[x][j];
}
// use of shift operator to make k = k/2
// after every iteration
k = k >> 1;
j++;
}
cout << L << "th level acestor of node "
<< temp << " is = " << x << endl;
return;
}
int main()
{
// n represent number of nodes
int n = 12;
1475
Chapter 248. Level Ancestor Problem
// initialization of ancestor matrix
// suppose max range of node is up to 1000
// if there are 1000 nodes than also length
// of ancestor matrix will not exceed 10
vector<vector<int> > ancestor(1000, vector<int>(10));
// this vector is used to store depth of each node.
vector<int> depth(1000);
// fill function is used to initialize depth with -1
fill(depth.begin(), depth.end(), -1);
// node array is used to store all nodes
int* node = new int[1000];
// isNode is an array to check whether a
// node is present in graph or not
int* isNode = new int[1000];
// memset function to initialize isNode array with 0
memset(isNode, 0, 1000 * sizeof(int));
// function to calculate len
// len -> it is the maximum length of array to
// hold ancestor of each node.
int len = getLen(n);
// R stores root node
R = 2;
// construction of graph
// here 0 represent that the node is root node
constructGraph(ancestor, node, depth, isNode, 2, 0, 0);
constructGraph(ancestor, node, depth, isNode, 5, 2, 1);
constructGraph(ancestor, node, depth, isNode, 3, 5, 2);
constructGraph(ancestor, node, depth, isNode, 4, 5, 3);
constructGraph(ancestor, node, depth, isNode, 1, 5, 4);
constructGraph(ancestor, node, depth, isNode, 7, 1, 5);
constructGraph(ancestor, node, depth, isNode, 9, 1, 6);
constructGraph(ancestor, node, depth, isNode, 10, 9, 7);
constructGraph(ancestor, node, depth, isNode, 11, 10, 8);
constructGraph(ancestor, node, depth, isNode, 6, 10, 9);
constructGraph(ancestor, node, depth, isNode, 8, 10, 10);
// function to pre compute ancestor matrix
setancestor(ancestor, depth, node, len, n);
1476
Chapter 248. Level Ancestor Problem
Output:
Source
https://www.geeksforgeeks.org/level-ancestor-problem/
1477
Chapter 249
1478
Chapter 249. Level Order Tree Traversal
for d = 1 to height(tree)
printGivenLevel(tree, d);
Implementation:
1479
Chapter 249. Level Order Tree Traversal
if (level == 1)
printf("%d ", root->data);
else if (level > 1)
{
printGivenLevel(root->left, level-1);
printGivenLevel(root->right, level-1);
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node->left);
int rheight = height(node->right);
/* use the larger one */
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
1480
Chapter 249. Level Order Tree Traversal
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Level Order traversal of binary tree is \n");
printLevelOrder(root);
return 0;
}
Java
1481
Chapter 249. Level Order Tree Traversal
Python
1482
Chapter 249. Level Order Tree Traversal
1483
Chapter 249. Level Order Tree Traversal
Output:
Time Complexity: O(n^2) in worst case. For a skewed tree, printGivenLevel() takes O(n)
time where n is the number of nodes in the skewed tree. So time complexity of printLevel-
Order() is O(n) + O(n-1) + O(n-2) + .. + O(1) which is O(n^2).
METHOD 2 (Use Queue)
Algorithm:
For each node, first the node is visited and then it’s child nodes are put in a FIFO queue.
printLevelorder(tree)
1) Create an empty queue q
2) temp_node = root /*start from root*/
3) Loop while temp_node is not NULL
a) print temp_node->data.
b) Enqueue temp_node’s children (first left then right children) to q
c) Dequeue a node from q and assign it’s value to temp_node
Implementation:
Here is a simple implementation of the above algorithm. Queue is implemented using an
array with maximum size of 500. We can implement queue as linked list also.
1484
Chapter 249. Level Order Tree Traversal
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* frunction prototypes */
struct node** createQueue(int *, int *);
void enQueue(struct node **, int *, struct node *);
struct node *deQueue(struct node **, int *);
/* Given a binary tree, print its nodes in level order
using array for implementing queue */
void printLevelOrder(struct node* root)
{
int rear, front;
struct node **queue = createQueue(&front, &rear);
struct node *temp_node = root;
while (temp_node)
{
printf("%d ", temp_node->data);
/*Enqueue left child */
if (temp_node->left)
enQueue(queue, &rear, temp_node->left);
/*Enqueue right child */
if (temp_node->right)
enQueue(queue, &rear, temp_node->right);
/*Dequeue node and make it temp_node*/
temp_node = deQueue(queue, &front);
}
}
/*UTILITY FUNCTIONS*/
struct node** createQueue(int *front, int *rear)
{
struct node **queue =
(struct node **)malloc(sizeof(struct node*)*MAX_Q_SIZE);
*front = *rear = 0;
return queue;
1485
Chapter 249. Level Order Tree Traversal
}
void enQueue(struct node **queue, int *rear, struct node *new_node)
{
queue[*rear] = new_node;
(*rear)++;
}
struct node *deQueue(struct node **queue, int *front)
{
(*front)++;
return queue[*front - 1];
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Level Order traversal of binary tree is \n");
printLevelOrder(root);
return 0;
}
C++
1486
Chapter 249. Level Order Tree Traversal
// A Binary Tree Node
struct Node
{
int data;
struct Node *left, *right;
};
// Iterative method to find height of Bianry Tree
void printLevelOrder(Node *root)
{
// Base Case
if (root == NULL) return;
// Create an empty queue for level order tarversal
queue<Node *> q;
// Enqueue Root and initialize height
q.push(root);
while (q.empty() == false)
{
// Print front of queue and remove it from queue
Node *node = q.front();
cout << node->data << " ";
q.pop();
/* Enqueue left child */
if (node->left != NULL)
q.push(node->left);
/*Enqueue right child */
if (node->right != NULL)
q.push(node->right);
}
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
1487
Chapter 249. Level Order Tree Traversal
{
// Let us create binary tree shown in above diagram
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Level Order traversal of binary tree is \n";
printLevelOrder(root);
return 0;
}
Java
1488
Chapter 249. Level Order Tree Traversal
Python
1489
Chapter 249. Level Order Tree Traversal
Output:
Source
https://www.geeksforgeeks.org/level-order-tree-traversal/
1490
Chapter 250
Method 1 (Recursive)
This problem can bee seen as an extension of the level order traversal post.
To print the nodes in spiral order, nodes at different levels should be printed in alternating
order. An additional Boolean variable ltr is used to change printing order of levels. If ltr is
1 then printGivenLevel() prints nodes from left to right else from right to left. Value of ltr
is flipped in each iteration to change the order.
Function to print level order traversal of tree
printSpiral(tree)
bool ltr = 0;
for d = 1 to height(tree)
printGivenLevel(tree, d, ltr);
ltr ~= ltr /*flip ltr*/
1491
Chapter 250. Level order traversal in spiral form
1492
Chapter 250. Level order traversal in spiral form
printGivenLevel(root, i, ltr);
/*Revert ltr to traverse next level in opposite order*/
ltr = !ltr;
}
}
/* Print nodes at a given level */
void printGivenLevel(struct node* root, int level, int ltr)
{
if(root == NULL)
return;
if(level == 1)
printf("%d ", root->data);
else if (level > 1)
{
if(ltr)
{
printGivenLevel(root->left, level-1, ltr);
printGivenLevel(root->right, level-1, ltr);
}
else
{
printGivenLevel(root->right, level-1, ltr);
printGivenLevel(root->left, level-1, ltr);
}
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node->left);
int rheight = height(node->right);
/* use the larger one */
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}
1493
Chapter 250. Level order traversal in spiral form
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
printf("Spiral Order traversal of binary tree is \n");
printSpiral(root);
return 0;
}
Java
1494
Chapter 250. Level order traversal in spiral form
class BinaryTree
{
Node root;
// Function to print the spiral traversal of tree
void printSpiral(Node node)
{
int h = height(node);
int i;
/* ltr -> left to right. If this variable is set then the
given label is transversed from left to right */
boolean ltr = false;
for (i = 1; i <= h; i++)
{
printGivenLevel(node, i, ltr);
/*Revert ltr to traverse next level in opposite order*/
ltr = !ltr;
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(Node node)
{
if (node == null)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node.left);
int rheight = height(node.right);
/* use the larger one */
if (lheight > rheight)
return (lheight + 1);
else
return (rheight + 1);
}
}
/* Print nodes at a given level */
void printGivenLevel(Node node, int level, boolean ltr)
{
1495
Chapter 250. Level order traversal in spiral form
Output:
Time Complexity: Worst case time complexity of the above method is O(n^2). Worst
case occurs in case of skewed trees.
Method 2 (Iterative)
We can print spiral order traversal in O(n) time and O(n) extra space. The idea is to use
two stacks. We can use one stack for printing from left to right and other stack for printing
from right to left. In every iteration, we have nodes of one level in one of the stacks. We
1496
Chapter 250. Level order traversal in spiral form
print the nodes, and push nodes of next level in other stack.
C++
1497
Chapter 250. Level order traversal in spiral form
{
struct node *temp = s2.top();
s2.pop();
cout << temp->data << " ";
// Note that is left is pushed before right
if (temp->left)
s1.push(temp->left);
if (temp->right)
s1.push(temp->right);
}
}
}
// A utility function to create a new node
struct node* newNode(int data)
{
struct node* node = new struct node;
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
cout << "Spiral Order traversal of binary tree is \n";
printSpiral(root);
return 0;
}
Java
1498
Chapter 250. Level order traversal in spiral form
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
static Node root;
void printSpiral(Node node)
{
if (node == null)
return; // NULL check
// Create two stacks to store alternate levels
Stack<Node> s1 = new Stack<Node>();// For levels to be printed from right to left
Stack<Node> s2 = new Stack<Node>();// For levels to be printed from left to right
// Push first level to first stack 's1'
s1.push(node);
// Keep ptinting while any of the stacks has some nodes
while (!s1.empty() || !s2.empty())
{
// Print nodes of current level from s1 and push nodes of
// next level to s2
while (!s1.empty())
{
Node temp = s1.peek();
s1.pop();
System.out.print(temp.data + " ");
// Note that is right is pushed before left
if (temp.right != null)
s2.push(temp.right);
if (temp.left != null)
s2.push(temp.left);
}
1499
Chapter 250. Level order traversal in spiral form
// Print nodes of current level from s2 and push nodes of
// next level to s1
while (!s2.empty())
{
Node temp = s2.peek();
s2.pop();
System.out.print(temp.data + " ");
// Note that is left is pushed before right
if (temp.left != null)
s1.push(temp.left);
if (temp.right != null)
s1.push(temp.right);
}
}
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(7);
tree.root.left.right = new Node(6);
tree.root.right.left = new Node(5);
tree.root.right.right = new Node(4);
System.out.println("Spiral Order traversal of Binary Tree is ");
tree.printSpiral(root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output:
Please write comments if you find any bug in the above program/algorithm; or if you want
to share more information about spiral traversal.
Source
https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/
1500
Chapter 251
Level order traversal in spiral form | Using one stack and one queue - GeeksforGeeks
Write a function to print spiral order traversal of a tree. For below tree, function should
print 1, 2, 3, 4, 5, 6, 7.
1501
Chapter 251. Level order traversal in spiral form | Using one stack and one queue
1502
Chapter 251. Level order traversal in spiral form | Using one stack and one queue
size--;
}
// print nodes from the stack if
// reverse is true
if (reverse) {
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
}
// the next row has to be printed as
// it is, hence change the value of
// reverse
reverse = !reverse;
}
}
/*Driver program to test the above functions*/
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
printSpiralUsingOneStack(root);
return 0;
}
Output:
1 2 3 4 5 6 7
Source
https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form-using-one-stack-and-one-queue/
1503
Chapter 252
Level order traversal line by line | Set 2 (Using Two Queues) - GeeksforGeeks
Given a Binary Tree, print the nodes level wise, each level on a new line.
Output:
1
2 3
4 5
1504
Chapter 252. Level order traversal line by line | Set 2 (Using Two Queues)
int data;
Node *left, *right;
};
// Prints level order traversal line by line
// using two queues.
void levelOrder(Node *root)
{
queue<Node *> q1, q2;
if (root == NULL)
return;
// Pushing first level node into first queue
q1.push(root);
// Executing loop till both the queues
// become empty
while (!q1.empty() || !q2.empty())
{
while (!q1.empty())
{
// Pushing left child of current node in
// first queue into second queue
if (q1.front()->left != NULL)
q2.push(q1.front()->left);
// pushing right child of current node
// in first queue into second queue
if (q1.front()->right != NULL)
q2.push(q1.front()->right);
cout << q1.front()->data << " ";
q1.pop();
}
cout << "\n";
while (!q2.empty())
{
// pushing left child of current node
// in second queue into first queue
if (q2.front()->left != NULL)
q1.push(q2.front()->left);
// pushing right child of current
// node in second queue into first queue
if (q2.front()->right != NULL)
1505
Chapter 252. Level order traversal line by line | Set 2 (Using Two Queues)
q1.push(q2.front()->right);
cout << q2.front()->data << " ";
q2.pop();
}
cout << "\n";
}
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(6);
levelOrder(root);
return 0;
}
Java
1506
Chapter 252. Level order traversal line by line | Set 2 (Using Two Queues)
Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
// Prints level order traversal line by line
// using two queues.
static void levelOrder(Node root)
{
Queue<Node> q1 = new LinkedList<Node>();
Queue<Node> q2 = new LinkedList<Node>();
if (root == null)
return;
// Pushing first level node into first queue
q1.add(root);
// Executing loop till both the queues
// become empty
while (!q1.isEmpty() || !q2.isEmpty())
{
while (!q1.isEmpty())
{
// Pushing left child of current node in
// first queue into second queue
if (q1.peek().left != null)
q2.add(q1.peek().left);
// pushing right child of current node
// in first queue into second queue
if (q1.peek().right != null)
q2.add(q1.peek().right);
System.out.print(q1.peek().data + " ");
q1.remove();
}
System.out.println();
while (!q2.isEmpty())
{
1507
Chapter 252. Level order traversal line by line | Set 2 (Using Two Queues)
Python
"""
Python program to do level order traversal
line by line using dual queue"""
class GFG:
"""Constructor to create a new tree node"""
def __init__(self,data):
self.val = data
self.left = None
self.right = None
"""Prints level order traversal line by
line using two queues."""
1508
Chapter 252. Level order traversal line by line | Set 2 (Using Two Queues)
def levelOrder(self,node):
q1 = [] # Queue 1
q2 = [] # Queue 2
q1.append(node)
"""Executing loop till both the
queues become empty"""
while(len(q1) > 0 or len(q2) > 0):
"""Empty string to concatenate
the string for q1"""
concat_str_q1 = ''
while(len(q1) > 0):
"""Poped node at the first
pos in queue 1 i.e q1"""
poped_node = q1.pop(0)
concat_str_q1 += poped_node.val +' '
"""Pushing left child of current
node in first queue into second queue"""
if poped_node.left:
q2.append(poped_node.left)
"""Pushing right child of current node
in first queue into second queue"""
if poped_node.right:
q2.append(poped_node.right)
print( str(concat_str_q1))
concat_str_q1 = ''
"""Empty string to concatenate the
string for q1"""
concat_str_q2 = ''
while (len(q2) > 0):
"""Poped node at the first pos
in queue 1 i.e q1"""
poped_node = q2.pop(0)
concat_str_q2 += poped_node.val + ' '
"""Pushing left child of current node
in first queue into first queue"""
if poped_node.left:
q1.append(poped_node.left)
"""Pushing right child of current node
in first queue into first queue"""
1509
Chapter 252. Level order traversal line by line | Set 2 (Using Two Queues)
if poped_node.right:
q1.append(poped_node.right)
print(str(concat_str_q2))
concat_str_q2 = ''
""" Driver program to test above functions"""
node = GFG("1")
node.left = GFG("2")
node.right = GFG("3")
node.left.left = GFG("4")
node.left.right = GFG("5")
node.right.right = GFG("6")
node.levelOrder(node)
# This code is contributed by Vaibhav Kumar 12
Output :
1
2 3
4 5 6
Source
https://www.geeksforgeeks.org/level-order-traversal-line-line-set-2-using-two-queues/
1510
Chapter 253
Level order traversal line by line | Set 3 (Using One Queue) - GeeksforGeeks
Given a Binary Tree, print the nodes level wise, each level on a new line.
Output:
1
2 3
4 5
1511
Chapter 253. Level order traversal line by line | Set 3 (Using One Queue)
{
struct node *left;
int data;
struct node *right;
};
// Function to do level order
// traversal line by line
void levelOrder(node *root)
{
if (root == NULL) return;
// Create an empty queue for
// level order tarversal
queue<node *> q;
// to store front element of
// queue.
node *curr;
// Enqueue Root and NULL node.
q.push(root);
q.push(NULL);
while (q.size() > 1)
{
curr = q.front();
q.pop();
// condition to check
// occurrence of next
// level.
if (curr == NULL)
{
q.push(NULL);
cout << "\n";
}
else {
// pushing left child of
// current node.
if(curr->left)
q.push(curr->left);
// pushing rigth child of
// current node.
if(curr->right)
1512
Chapter 253. Level order traversal line by line | Set 3 (Using One Queue)
q.push(curr->right);
cout << curr->data << " ";
}
}
}
// Utility function to create a
// new tree node
node* newNode(int data)
{
node *temp = new node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// Driver program to test above
// functions
int main()
{
// Let us create binary tree
// shown above
node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(6);
levelOrder(root);
return 0;
}
// This code is contributed by
// Nikhil Jindal.
Java
1513
Chapter 253. Level order traversal line by line | Set 3 (Using One Queue)
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
left = null;
right = null;
}
}
// Prints level order traversal line
// by line using two queues.
static void levelOrder(Node root) {
if (root == null)
return;
Queue<Node> q = new LinkedList<>();
// Pushing root node into the queue.
q.add(root);
// Pushing delimiter into the queue.
q.add(null);
// Executing loop till queue becomes
// empty
while (!q.isEmpty()) {
Node curr = q.poll();
// condition to check the
// occurence of next level
if (curr == null) {
if (!q.isEmpty()) {
q.add(null);
System.out.println();
}
} else {
// Pushing left child current node
if (curr.left != null)
q.add(curr.left);
// Pushing right child current node
if (curr.right != null)
q.add(curr.right);
System.out.print(curr.data + " ");
1514
Chapter 253. Level order traversal line by line | Set 3 (Using One Queue)
}
}
}
// Driver function
public static void main(String[] args) {
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.right = new Node(6);
levelOrder(root);
}
}
// This code is Contributed by Rishabh Jindal
Output :
1
2 3
4 5 6
Source
https://www.geeksforgeeks.org/level-order-traversal-line-line-set-3-using-one-queue/
1515
Chapter 254
Level order traversal with direction change after every two levels - GeeksforGeeks
Given a binary tree, print the level order traversal in such a way that first two levels are
printed from left to right, next two levels are printed from right to left, then next two from
left to right and so on. So, the problem is to reverse the direction of level order traversal of
binary tree after every two levels.
Examples:
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ / \ / \ / \
8 9 3 1 4 2 7 2
/ / \ \
16 17 18 19
Output:
1
2 3
7 6 5 4
2 7 2 4 1 3 9 8
16 17 18 19
In the above example, first two levels
are printed from left to right, next two
1516
Chapter 254. Level order traversal with direction change after every two levels
Approach:
We make use of queue and stack here. Queue is used for performing normal level order
traversal. Stack is used for reversing the direction of traversal after every two levels.
While doing normal level order traversal, first two levels nodes are printed at the time when
they are popped out from the queue. For the next two levels, we instead of printing the
nodes, pushed them onto the stack. When all nodes of current level are popped out, we
print the nodes in the stack. In this way, we print the nodes in right to left order by making
use of the stack. Now for the next two levels we again do normal level order traversal for
printing nodes from left to right. Then for the next two nodes, we make use of the stack for
achieving right to left order.
In this way, we will achieve desired modified level order traversal by making use of queue
and stack.
1517
Chapter 254. Level order traversal with direction change after every two levels
/* Maintain a stack for printing nodes in reverse
order after they are popped out from queue.*/
stack<Node*> myStack;
struct Node* temp = NULL;
// sz is used for storing the count of nodes in a level
int sz;
// Used for changing the direction of level order traversal
int ct = 0;
// Used for changing the direction of level order traversal
bool rightToLeft = false;
// Push root node to the queue
myQueue.push(node);
// Run this while loop till queue got empty
while (!myQueue.empty()) {
ct++;
sz = myQueue.size();
// Do a normal level order traversal
for (int i = 0; i < sz; i++) {
temp = myQueue.front();
myQueue.pop();
/*For printing nodes from left to right,
simply print the nodes in the order in which
they are being popped out from the queue.*/
if (rightToLeft == false)
cout << temp->data << " ";
/* For printing nodes from right to left,
push the nodes to stack instead of printing them.*/
else
myStack.push(temp);
if (temp->left)
myQueue.push(temp->left);
if (temp->right)
myQueue.push(temp->right);
}
1518
Chapter 254. Level order traversal with direction change after every two levels
1519
Chapter 254. Level order traversal with direction change after every two levels
root->right->left->right = newNode(2);
root->right->right->left = newNode(7);
root->right->right->right = newNode(2);
root->left->right->left->left = newNode(16);
root->left->right->left->right = newNode(17);
root->right->left->right->left = newNode(18);
root->right->right->left->right = newNode(19);
modifiedLevelOrder(root);
return 0;
}
Output:
1
2 3
7 6 5 4
2 7 2 4 1 3 9 8
16 17 18 19
Time Complexity: Each node is traversed at most twice while doing level order traversal,
so time complexity would be O(n).
Approach 2:
We make use of queue and stack here, but in a different way. Using macros #define
ChangeDirection(Dir) ((Dir) = 1 – (Dir)). In following implementation directs the order of
push operations in both queue or stack.
In this way, we will achieve desired modified level order traversal by making use of queue
and stack.
1520
Chapter 254. Level order traversal with direction change after every two levels
1521
Chapter 254. Level order traversal with direction change after every two levels
if (temp->left)
Q.push(temp->left);
}
}
cout << endl;
// for printing the nodes in order
// from right to left
while (!Q.empty())
{
temp = Q.front();
Q.pop();
cout << temp->data << " ";
if (dir == LEFT) {
if (temp->left)
S.push(temp->left);
if (temp->right)
S.push(temp->right);
} else {
if (temp->right)
S.push(temp->right);
if (temp->left)
S.push(temp->left);
}
}
cout << endl;
// Change the direction of traversal.
ChangeDirection(dir);
}
}
// Driver program to test above functions
int main()
{
// Let us create binary tree
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->left->left->right = newNode(9);
root->left->right->left = newNode(3);
1522
Chapter 254. Level order traversal with direction change after every two levels
root->left->right->right = newNode(1);
root->right->left->left = newNode(4);
root->right->left->right = newNode(2);
root->right->right->left = newNode(7);
root->right->right->right = newNode(2);
root->left->right->left->left = newNode(16);
root->left->right->left->right = newNode(17);
root->right->left->right->left = newNode(18);
root->right->right->left->right = newNode(19);
modifiedLevelOrder(root);
return 0;
}
Output:
1
2 3
7 6 5 4
2 7 2 4 1 3 9 8
16 17 18 19
Time Complexity: every node is also traversed twice. There time complexity is still O(n).
Improved By : vhinf2047
Source
https://www.geeksforgeeks.org/level-order-traversal-direction-change-every-two-levels/
1523
Chapter 255
Input :
2
/ \
1 3
/ \ \
4 6 8
/
5
Output : 2
2
/ \
1 3
/ \ \
4 6 8 [Level with maximum nodes = 3]
/
5
We know that in level order traversal of binary tree with queue, at any time our queue
contains all elements of a particular level. So find level with maximum number of nodes in
queue.
1524
Chapter 255. Level with maximum number of nodes
1525
Chapter 255. Level with maximum number of nodes
1526
Chapter 255. Level with maximum number of nodes
Output:
Source
https://www.geeksforgeeks.org/level-maximum-number-nodes/
1527
Chapter 256
1528
Chapter 256. Levelwise Alternating GCD and LCM of nodes in Segment Tree
The operations (GCD) and (LCM) indicate which operation was carried out to merge the
child nodes
Given N leaf nodes, the task is to build such a segment tree and print the root node.
Examples:
Careful analysis of the image suggests that if the height of the tree is even then the root node
is a result of LCM operation of its left and right children else a result of GCD operation.
#include <bits/stdc++.h>
using namespace std;
// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
// Everything divides 0
if (a == 0 || b == 0)
return 0;
// base case
if (a == b)
return a;
1529
Chapter 256. Levelwise Alternating GCD and LCM of nodes in Segment Tree
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
// A utility function to get the middle index from
// corner indexes.
int getMid(int s, int e) { return s + (e - s) / 2; }
void STconstructUtill(int arr[], int ss, int se, int* st,
int si, int op)
{
// If there is one element in array, store it in
// current node of segment tree and return
if (ss == se) {
st[si] = arr[ss];
return;
}
// If there are more than one elements, then recur
// for left and right subtrees and store the sum of
// values in this node
int mid = getMid(ss, se);
// Build the left and the right subtrees by using
// the fact that operation at level (i + 1) = !
// (operation at level i)
STconstructUtill(arr, ss, mid, st, si * 2 + 1, !op);
STconstructUtill(arr, mid + 1, se, st, si * 2 + 2, !op);
// merge the left and right subtrees by checking
// the operation to be carried. If operation = 1,
// then do GCD else LCM
if (op == 1) {
// GCD operation
st[si] = __gcd(st[2 * si + 1], st[2 * si + 2]);
}
else {
// LCM operation
st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
(gcd(st[2 * si + 1], st[2 * si + 2]));
}
}
/* Function to construct segment tree from given array.
This function allocates memory for segment tree and
calls STconstructUtil() to fill the allocated memory */
1530
Chapter 256. Levelwise Alternating GCD and LCM of nodes in Segment Tree
Output:
Time complexity for tree construction is O(n), as there are total 2*n-1 nodes and value at
every node us calculated at once.
Now to perform point updates i.e. update the value with given index and value, can be
done by traversing down the tree to the leaf node and performing the update.
1531
Chapter 256. Levelwise Alternating GCD and LCM of nodes in Segment Tree
While coming back to the root node we build the tree again similar to the build() function
by passing the operation to be performed at every level and storing the result of applying
that operation on values of its left and right children and storing the result into that node.
Consider the following Segment tree after performing the update,
arr[2] = 7
Now the updated segment tree looks like this:
Here nodes in black denote the fact that they are updated.
#include <bits/stdc++.h>
using namespace std;
// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
// Everything divides 0
if (a == 0 || b == 0)
return 0;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
1532
Chapter 256. Levelwise Alternating GCD and LCM of nodes in Segment Tree
}
// A utility function to get the middle index from
// corner indexes.
int getMid(int s, int e) { return s + (e - s) / 2; }
void STconstructUtill(int arr[], int ss, int se, int* st,
int si, int op)
{
// If there is one element in array, store it in
// current node of segment tree and return
if (ss == se) {
st[si] = arr[ss];
return;
}
// If there are more than one elements, then recur
// for left and right subtrees and store the sum of
// values in this node
int mid = getMid(ss, se);
// Build the left and the right subtrees by using
// the fact that operation at level (i + 1) = !
// (operation at level i)
STconstructUtill(arr, ss, mid, st, si * 2 + 1, !op);
STconstructUtill(arr, mid + 1, se, st, si * 2 + 2, !op);
// merge the left and right subtrees by checking
// the operation to be carried. If operation = 1,
// then do GCD else LCM
if (op == 1) {
// GCD operation
st[si] = gcd(st[2 * si + 1], st[2 * si + 2]);
}
else {
// LCM operation
st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
(gcd(st[2 * si + 1], st[2 * si + 2]));
}
}
void updateUtil(int* st, int ss, int se, int ind, int val,
int si, int op)
{
// Base Case: If the input index lies outside
// this segment
if (ind < ss || ind > se)
return;
1533
Chapter 256. Levelwise Alternating GCD and LCM of nodes in Segment Tree
// If the input index is in range of this node,
// then update the value of the node and its
// children
// leaf node
if (ss == se && ss == ind) {
st[si] = val;
return;
}
int mid = getMid(ss, se);
// Update the left and the right subtrees by
// using the fact that operation at level
// (i + 1) = ! (operation at level i)
updateUtil(st, ss, mid, ind, val, 2 * si + 1, !op);
updateUtil(st, mid + 1, se, ind, val, 2 * si + 2, !op);
// merge the left and right subtrees by checking
// the operation to to be carried. If operation = 1,
// then do GCD else LCM
if (op == 1) {
// GCD operation
st[si] = gcd(st[2 * si + 1], st[2 * si + 2]);
}
else {
// LCM operation
st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
(gcd(st[2 * si + 1], st[2 * si + 2]));
}
}
void update(int arr[], int* st, int n, int ind, int val)
{
// Check for erroneous input index
if (ind < 0 || ind > n - 1) {
printf("Invalid Input");
return;
}
// Height of segment tree
int x = (int)(ceil(log2(n)));
// operation = 1(GCD) if Height of tree is
// even else it is 0(LCM) for the root node
1534
Chapter 256. Levelwise Alternating GCD and LCM of nodes in Segment Tree
1535
Chapter 256. Levelwise Alternating GCD and LCM of nodes in Segment Tree
// perform update arr[2] = 7
update(arr, st, n, 2, 7);
cout << "New Value at Root Node = " <<
st[rootIndex] << endl;
return 0;
}
Output:
The time complexity of update is also O(Logn). To update a leaf value, one node is processed
at every level and number of levels is O(Logn).
Source
https://www.geeksforgeeks.org/levelwise-alternating-gcd-lcm-nodes-segment-tree/
1536
Chapter 257
1
/ \
2 3
1
/ \
2 3
/ \ /
4 5 6
1
/ \
2 3
/ /
4 5
1537
Chapter 257. Linked complete binary tree & its creation
1
/ \
2 3
/ \ /
4 5 6
/
7
Complete binary trees are generally represented using arrays. The array representation is
better because it doesn’t contain any empty slot. Given parent index i, its left child is given
by 2 * i + 1 and its right child is given by 2 * i + 2. So no extra space is wasted and space
to store left and right pointers is saved. However, it may be an interesting programming
question to create a Complete Binary Tree using linked representation. Here Linked mean
a non-array representation where left and right pointers(or references) are used to refer left
and right children respectively. How to write an insert function that always adds a new
node in the last level and at the leftmost available position?
To create a linked complete binary tree, we need to keep track of the nodes in a level order
fashion such that the next node to be inserted lies in the leftmost position. A queue data
structure can be used to keep track of the inserted nodes.
Following are steps to insert a new node in Complete Binary Tree.
1. If the tree is empty, initialize the root with new node.
2. Else, get the front node of the queue.
…….If the left child of this front node doesn’t exist, set the left child as the new node.
…….else if the right child of this front node doesn’t exist, set the right child as the new node.
3. If the front node has both the left child and right child, Dequeue() it.
4. Enqueue() the new node.
Below is the implementation:
1538
Chapter 257. Linked complete binary tree & its creation
1539
Chapter 257. Linked complete binary tree & its creation
queue->array[++queue->rear] = root;
if (isEmpty(queue))
++queue->front;
}
struct node* Dequeue(struct Queue* queue)
{
if (isEmpty(queue))
return NULL;
struct node* temp = queue->array[queue->front];
if (hasOnlyOneItem(queue))
queue->front = queue->rear = -1;
else
++queue->front;
return temp;
}
struct node* getFront(struct Queue* queue)
{ return queue->array[queue->front]; }
// A utility function to check if a tree node has both left and right children
int hasBothChild(struct node* temp)
{
return temp && temp->left && temp->right;
}
// Function to insert a new node in complete binary tree
void insert(struct node **root, int data, struct Queue* queue)
{
// Create a new node for given data
struct node *temp = newNode(data);
// If the tree is empty, initialize the root with new node.
if (!*root)
*root = temp;
else
{
// get the front node of the queue.
struct node* front = getFront(queue);
// If the left child of this front node doesn’t exist, set the
// left child as the new node
if (!front->left)
1540
Chapter 257. Linked complete binary tree & its creation
front->left = temp;
// If the right child of this front node doesn’t exist, set the
// right child as the new node
else if (!front->right)
front->right = temp;
// If the front node has both the left child and right child,
// Dequeue() it.
if (hasBothChild(front))
Dequeue(queue);
}
// Enqueue() the new node for later insertions
Enqueue(temp, queue);
}
// Standard level order traversal to test above function
void levelOrder(struct node* root)
{
struct Queue* queue = createQueue(SIZE);
Enqueue(root, queue);
while (!isEmpty(queue))
{
struct node* temp = Dequeue(queue);
printf("%d ", temp->data);
if (temp->left)
Enqueue(temp->left, queue);
if (temp->right)
Enqueue(temp->right, queue);
}
}
// Driver program to test above functions
int main()
{
struct node* root = NULL;
struct Queue* queue = createQueue(SIZE);
int i;
for(i = 1; i <= 12; ++i)
insert(&root, i, queue);
1541
Chapter 257. Linked complete binary tree & its creation
levelOrder(root);
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10 11 12
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please
write comments if you find anything incorrect, or you want to share more information about
the topic discussed above.
Source
https://www.geeksforgeeks.org/linked-complete-binary-tree-its-creation/
1542
Chapter 258
Locking and Unlocking of Resources arranged in the form of n-ary Tree - GeeksforGeeks
Given an n-ary tree of resources arranged hierarchically such that height of tree is O(Log N)
where N is total number of nodes (or resources). A process needs to lock a resource node in
order to use it. But a node cannot be locked if any of its descendant or ancestor is locked.
Following operations are required for a given resource node:
• islock()- returns true if a given node is locked and false if it is not. A node is locked
if lock() has successfully executed for the node.
• Lock()- locks the given node if possible and updates lock information. Lock is possible
only if ancestors and descendants of current node are not locked.
• unLock()- unlocks the node and updates information.
How design resource nodes and implement above operations such that following time com-
plexities are achieved.
islock() O(1)
Lock() O(log N)
unLock() O(log N)
We strongly recommend you to minimize your browser and try this yourself
first.
It is given that resources need to be stored in the form of n-ary tree. Now the question is,
how to augment the tree to achieve above complexity bounds.
1543
Chapter 258. Locking and Unlocking of Resources arranged in the form of n-ary Tree
Method 1 (Simple)
A Simple Solution is to store a boolean variable isLocked with every resource node. The
boolean variable isLocked is true if current node is locked, else false.
Let us see how operations work using this Approach.
Time Complexities:
isLock() O(1)
Lock() O(N)
unLock() O(1)
1544
Chapter 258. Locking and Unlocking of Resources arranged in the form of n-ary Tree
Source
https://www.geeksforgeeks.org/locking-and-unlocking-of-resources-in-the-form-of-n-ary-tree/
1545
Chapter 259
Input :
2
/ \
7 2
/ \ \
1 1 2
Output : 2
Input :
4
/ \
4 4
/ \ \
4 9 5
Output : 3
The idea is to recursively traverse given binary tree. We can think of any path (of nodes
with the same values) in up to two directions(left and right) from it’s root. Then, for each
node, we want to know what is the longest possible length extending in the left and the
longest possible length extending in the right directions. The longest length that extends
1546
Chapter 259. Longest Path with Same Values in a Binary Tree
from the node will be 1 + length(node->left) if node->left exists, and has the same value
as node. Similarly for the node->right case.
While we are computing lengths, each candidate answer will be the sum of the lengths in
both directions from that node. We keep updating these answers and return the maximum
one.
1547
Chapter 259. Longest Path with Same Values in a Binary Tree
return ans;
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node *newNode(int data) {
Node *temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver code
int main() {
/* Let us construct a Binary Tree
4
/ \
4 4
/ \ \
4 9 5 */
Node *root = NULL;
root = newNode(4);
root->left = newNode(4);
root->right = newNode(4);
root->left->left = newNode(4);
root->left->right = newNode(9);
root->right->right = newNode(5);
cout << longestSameValuePath(root);
return 0;
}
Complexity Analysis:
• Time complexity : O(n), where n is the number of nodes in tree as every node is
processed once.
• Auxiliary Space : O(h), where h is the height of tree as recursion can go upto depth
h.
Source
https://www.geeksforgeeks.org/longest-path-values-binary-tree/
1548
Chapter 260
In below diagram binary tree with longest consecutive path(LCP) are shown :
We can solve above problem recursively. At each node we need information of its parent
node, if current node has value one more than its parent node then it makes a consecutive
path, at each node we will compare node’s value with its parent value and update the longest
consecutive path accordingly.
For getting the value of parent node, we will pass the (node_value + 1) as an argument
to the recursive method and compare the node value with this argument value, if satisfies,
update the current length of consecutive path otherwise reinitialize current path length by
1.
Please see below code for better understanding :
1549
Chapter 260. Longest consecutive sequence in Binary tree
struct Node
{
int data;
Node *left, *right;
};
// A utility function to create a node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Utility method to return length of longest
// consecutive sequence of tree
void longestConsecutiveUtil(Node* root, int curLength,
int expected, int& res)
{
if (root == NULL)
return;
// if root data has one more than its parent
// then increase current length
if (root->data == expected)
curLength++;
else
curLength = 1;
// update the maximum by current length
res = max(res, curLength);
// recursively call left and right subtree with
// expected value 1 more than root data
longestConsecutiveUtil(root->left, curLength,
root->data + 1, res);
longestConsecutiveUtil(root->right, curLength,
root->data + 1, res);
}
// method returns length of longest consecutive
// sequence rooted at node root
int longestConsecutive(Node* root)
{
if (root == NULL)
return 0;
1550
Chapter 260. Longest consecutive sequence in Binary tree
int res = 0;
// call utility method with current length 0
longestConsecutiveUtil(root, 0, root->data, res);
return res;
}
// Driver code to test above methods
int main()
{
Node* root = newNode(6);
root->right = newNode(9);
root->right->left = newNode(7);
root->right->right = newNode(10);
root->right->right->right = newNode(11);
printf("%d\n", longestConsecutive(root));
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/longest-consecutive-sequence-binary-tree/
1551
Chapter 261
This problem is same as diameter of n-ary tree. We have discussed a simple solution here.
In this post, an efficient solution is discussed. We can find longest path using two BFSs.
The idea is based on the following fact: If we start BFS from any node x and find a node
with the longest distance from x, it must be an end point of the longest path. It can be
proved using contradiction. So our algorithm reduces to simple two BFSs. First BFS to
find an end point of the longest path and second BFS from this end point to find the actual
longest path.
As we can see in above diagram, if we start our BFS from node-0, the node at the farthest
distance from it will be node-5, now if we start our BFS from node-5 the node at the farthest
distance will be node-7, finally, path from node-5 to node-7 will constitute our longest path.
1552
Chapter 261. Longest path in an undirected tree
// This class represents a undirected graph using adjacency list
class Graph
{
int V; // No. of vertices
list<int> *adj; // Pointer to an array containing
// adjacency lists
public:
Graph(int V); // Constructor
void addEdge(int v, int w);// function to add an edge to graph
void longestPathLength(); // prints longest path of the tree
pair<int, int> bfs(int u); // function returns maximum distant
// node from u with its distance
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
adj[w].push_back(v); // Since the graph is undirected
}
// method returns farthest node and its distance from node u
pair<int, int> Graph::bfs(int u)
{
// mark all distance with -1
int dis[V];
memset(dis, -1, sizeof(dis));
queue<int> q;
q.push(u);
// distance of u from u will be 0
dis[u] = 0;
while (!q.empty())
{
int t = q.front(); q.pop();
// loop for all adjacent nodes of node-t
for (auto it = adj[t].begin(); it != adj[t].end(); it++)
{
int v = *it;
1553
Chapter 261. Longest path in an undirected tree
// push node into queue only if
// it is not visited already
if (dis[v] == -1)
{
q.push(v);
// make distance of v, one more
// than distance of t
dis[v] = dis[t] + 1;
}
}
}
int maxDis = 0;
int nodeIdx;
// get farthest node distance and its index
for (int i = 0; i < V; i++)
{
if (dis[i] > maxDis)
{
maxDis = dis[i];
nodeIdx = i;
}
}
return make_pair(nodeIdx, maxDis);
}
// method prints longest path of given tree
void Graph::longestPathLength()
{
pair<int, int> t1, t2;
// first bfs to find one end point of
// longest path
t1 = bfs(0);
// second bfs to find actual longest path
t2 = bfs(t1.first);
cout << "Longest path is from " << t1.first << " to "
<< t2.first << " of length " << t2.second;
}
// Driver code to test above methods
int main()
{
1554
Chapter 261. Longest path in an undirected tree
Output:
Source
https://www.geeksforgeeks.org/longest-path-undirected-tree/
1555
Chapter 262
1556
Chapter 262. Longest word in ternary search tree
1557
Chapter 262. Longest word in ternary search tree
if (*(word+1))
insert(&( (*root)->eq ), word+1);
// the last character of the word
else
(*root)->isEndOfString = 1;
}
}
// Function to find max of three numbers
int max(int a, int b, int c)
{
int max;
if (a >= b && a >= c)
max = a;
else if (b >= a && b >= c)
max = b;
else
max = c;
}
// Function to find length of largest word in TST
int maxLengthTST(struct Node *root)
{
if (root == NULL)
return 0;
return max(maxLengthTST(root->left),
maxLengthTST(root->eq)+1,
maxLengthTST(root->right));
}
// Driver program to test above functions
int main()
{
struct Node *root = NULL;
insert(&root, "Prakriti");
insert(&root, "Raghav");
insert(&root, "Rashi");
insert(&root, "Sunidhi");
int value = maxLengthTST(root);
printf("Length of largest word in "
"ternary search tree is: %d\n", value);
return 0;
}
Java
1558
Chapter 262. Longest word in ternary search tree
1559
Chapter 262. Longest word in ternary search tree
1560
Chapter 262. Longest word in ternary search tree
Output:
Source
https://www.geeksforgeeks.org/longest-word-ternary-search-tree/
1561
Chapter 263
1562
Chapter 263. Lowest Common Ancestor in Parent Array Representation
// Maximum value in a node
const int MAX = 1000;
// Function to find the Lowest common ancestor
int findLCA(int n1, int n2, int parent[])
{
// Create a visited vector and mark
// all nodes as not visited.
vector<bool> visited(MAX, false);
visited[n1] = true;
// Moving from n1 node till root and
// mark every accessed node as visited
while (parent[n1] != -1) {
visited[n1] = true;
// Move to the parent of node n1
n1 = parent[n1];
}
visited[n1] = true;
// For second node finding the first
// node common
while (!visited[n2])
n2 = parent[n2];
return n2;
}
// Insert function for Binary tree
void insertAdj(int parent[], int i, int j)
{
parent[i] = j;
}
// Driver Functiom
int main()
{
// Maximum capacity of binary tree
int parent[MAX];
// Root marked
parent[20] = -1;
insertAdj(parent, 8, 20);
insertAdj(parent, 22, 20);
1563
Chapter 263. Lowest Common Ancestor in Parent Array Representation
insertAdj(parent, 4, 8);
insertAdj(parent, 12, 8);
insertAdj(parent, 10, 12);
insertAdj(parent, 14, 12);
cout << findLCA(10, 14, parent);
return 0;
}
Output:
12
Time Complexity – The time complexity of the above algorithm is O(log n) as it requires
O(log n) time in searching.
Source
https://www.geeksforgeeks.org/lowest-common-ancestor-in-parent-array-representation/
1564
Chapter 264
LCA of 10 and 14 is 12
LCA of 14 and 8 is 8
LCA of 10 and 22 is 20
1565
Chapter 264. Lowest Common Ancestor in a Binary Search Tree.
node, if it’s is smaller than both n1 and n2, then LCA lies on right side. Otherwise root is
LCA (assuming that both n1 and n2 are present in BST)
C
1566
Chapter 264. Lowest Common Ancestor in a Binary Search Tree.
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
int n1 = 10, n2 = 14;
struct node *t = lca(root, n1, n2);
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
n1 = 14, n2 = 8;
t = lca(root, n1, n2);
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
n1 = 10, n2 = 22;
t = lca(root, n1, n2);
printf("LCA of %d and %d is %d \n", n1, n2, t->data);
getchar();
return 0;
}
Java
1567
Chapter 264. Lowest Common Ancestor in a Binary Search Tree.
// If both n1 and n2 are smaller than root, then LCA lies in left
if (node.data > n1 && node.data > n2)
return lca(node.left, n1, n2);
// If both n1 and n2 are greater than root, then LCA lies in right
if (node.data < n1 && node.data < n2)
return lca(node.right, n1, n2);
return node;
}
/* Driver program to test lca() */
public static void main(String args[])
{
// Let us construct the BST shown in the above figure
BinaryTree tree = new BinaryTree();
tree.root = new Node(20);
tree.root.left = new Node(8);
tree.root.right = new Node(22);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(12);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(14);
int n1 = 10, n2 = 14;
Node t = tree.lca(tree.root, n1, n2);
System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);
n1 = 14;
n2 = 8;
t = tree.lca(tree.root, n1, n2);
System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);
n1 = 10;
n2 = 22;
t = tree.lca(tree.root, n1, n2);
System.out.println("LCA of " + n1 + " and " + n2 + " is " + t.data);
}
}
// This code has been contributed by Mayank Jaiswal
Python
1568
Chapter 264. Lowest Common Ancestor in a Binary Search Tree.
1569
Chapter 264. Lowest Common Ancestor in a Binary Search Tree.
n1 = 10 ; n2 = 22
t = lca(root, n1, n2)
print "LCA of %d and %d is %d" %(n1, n2, t.data)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
LCA of 10 and 14 is 12
LCA of 14 and 8 is 8
LCA of 10 and 22 is 20
Time complexity of above solution is O(h) where h is height of tree. Also, the above solution
requires O(h) extra space in function call stack for recursive function calls. We can avoid
extra space using iterative solution.
/* Function to find LCA of n1 and n2. The function assumes that both
n1 and n2 are present in BST */
struct node *lca(struct node* root, int n1, int n2)
{
while (root != NULL)
{
// If both n1 and n2 are smaller than root, then LCA lies in left
if (root->data > n1 && root->data > n2)
root = root->left;
// If both n1 and n2 are greater than root, then LCA lies in right
else if (root->data < n1 && root->data < n2)
root = root->right;
else break;
}
return root;
}
1570
Chapter 264. Lowest Common Ancestor in a Binary Search Tree.
Source
https://www.geeksforgeeks.org/lowest-common-ancestor-in-a-binary-search-tree/
1571
Chapter 265
We have discussed an efficient solution to find LCA in Binary Search Tree. In Binary Search
Tree, using BST properties, we can find LCA in O(h) time where h is height of tree. Such
1572
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
an implementation is not possible in Binary Tree as keys Binary Tree nodes don’t follow
any order. Following are different approaches to find LCA in Binary Tree.
Method 1 (By Storing root to n1 and root to n2 paths):
Following is simple O(n) algorithm to find LCA of n1 and n2.
1) Find path from root to n1 and store it in a vector or array.
2) Find path from root to n2 and store it in another vector or array.
3) Traverse both paths till the values in arrays are same. Return the common element just
before the mismatch.
Following is the implementation of above algorithm.
C++
1573
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
if (root->key == k)
return true;
// Check if k is found in left or right sub-tree
if ( (root->left && findPath(root->left, path, k)) ||
(root->right && findPath(root->right, path, k)) )
return true;
// If not present in subtree rooted with root, remove root from
// path[] and return false
path.pop_back();
return false;
}
// Returns LCA if node n1, n2 are present in the given binary tree,
// otherwise return -1
int findLCA(Node *root, int n1, int n2)
{
// to store paths to n1 and n2 from the root
vector<int> path1, path2;
// Find paths from root to n1 and root to n1. If either n1 or n2
// is not present, return -1
if ( !findPath(root, path1, n1) || !findPath(root, path2, n2))
return -1;
/* Compare the paths to get the first different value */
int i;
for (i = 0; i < path1.size() && i < path2.size() ; i++)
if (path1[i] != path2[i])
break;
return path1[i-1];
}
// Driver program to test above functions
int main()
{
// Let us create the Binary Tree shown in above diagram.
Node * root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
cout << "LCA(4, 5) = " << findLCA(root, 4, 5);
cout << "nLCA(4, 6) = " << findLCA(root, 4, 6);
cout << "nLCA(3, 4) = " << findLCA(root, 3, 4);
1574
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
Java
1575
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
if (!path1.get(i).equals(path2.get(i)))
break;
}
return path1.get(i-1);
}
// Finds the path from root node to given root of the tree, Stores the
// path in a vector path[], returns true if path exists otherwise false
private boolean findPath(Node root, int n, List<Integer> path)
{
// base case
if (root == null) {
return false;
}
// Store this node . The node will be removed if
// not in path from root to n.
path.add(root.data);
if (root.data == n) {
return true;
}
if (root.left != null && findPath(root.left, n, path)) {
return true;
}
if (root.right != null && findPath(root.right, n, path)) {
return true;
}
// If not present in subtree rooted with root, remove root from
// path[] and return false
path.remove(path.size()-1);
return false;
}
// Driver code
public static void main(String[] args)
{
BT_NoParentPtr_Solution1 tree = new BT_NoParentPtr_Solution1();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
1576
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
Python
1577
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
Output:
LCA(4, 5) = 2
LCA(4, 6) = 1
1578
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
LCA(3, 4) = 1
LCA(2, 4) = 2
Time Complexity: Time complexity of the above solution is O(n). The tree is traversed
twice, and then path arrays are compared.
Thanks to Ravi Chandra Enaganti for suggesting the initial solution based on this method.
Method 2 (Using Single Traversal)
The method 1 finds LCA in O(n) time, but requires three tree traversals plus extra spaces
for path arrays. If we assume that the keys n1 and n2 are present in Binary Tree, we can
find LCA using single traversal of Binary Tree and without extra storage for path arrays.
The idea is to traverse the tree starting from root. If any of the given keys (n1 and n2)
matches with root, then root is LCA (assuming that both keys are present). If root doesn’t
match with any of the keys, we recur for left and right subtree. The node which has one
key present in its left subtree and the other key present in right subtree is the LCA. If both
keys lie in left subtree, then left subtree has LCA also, otherwise LCA lies in right subtree.
C++
/* C++ Program to find LCA of n1 and n2 using one traversal of Binary Tree */
#include <iostream>
using namespace std;
// A Binary Tree Node
struct Node
{
struct Node *left, *right;
int key;
};
// Utility function to create a new tree Node
Node* newNode(int key)
{
Node *temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
// This function returns pointer to LCA of two given values n1 and n2.
// This function assumes that n1 and n2 are present in Binary Tree
struct Node *findLCA(struct Node* root, int n1, int n2)
{
// Base case
if (root == NULL) return NULL;
// If either n1 or n2 matches with root's key, report
// the presence by returning root (Note that if a key is
1579
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
Java
1580
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
{
data = item;
left = right = null;
}
}
public class BinaryTree
{
//Root of the Binary Tree
Node root;
Node findLCA(int n1, int n2)
{
return findLCA(root, n1, n2);
}
// This function returns pointer to LCA of two given
// values n1 and n2. This function assumes that n1 and
// n2 are present in Binary Tree
Node findLCA(Node node, int n1, int n2)
{
// Base case
if (node == null)
return null;
// If either n1 or n2 matches with root's key, report
// the presence by returning root (Note that if a key is
// ancestor of other, then the ancestor key becomes LCA
if (node.data == n1 || node.data == n2)
return node;
// Look for keys in left and right subtrees
Node left_lca = findLCA(node.left, n1, n2);
Node right_lca = findLCA(node.right, n1, n2);
// If both of the above calls return Non-NULL, then one key
// is present in once subtree and other is present in other,
// So this node is the LCA
if (left_lca!=null && right_lca!=null)
return node;
// Otherwise check if left subtree or right subtree is LCA
return (left_lca != null) ? left_lca : right_lca;
}
/* Driver program to test above functions */
public static void main(String args[])
{
1581
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
Python
1582
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
# Look for keys in left and right subtrees
left_lca = findLCA(root.left, n1, n2)
right_lca = findLCA(root.right, n1, n2)
# If both of the above calls return Non-NULL, then one key
# is present in once subtree and other is present in other,
# So this node is the LCA
if left_lca and right_lca:
return root
# Otherwise check if left subtree or right subtree is LCA
return left_lca if left_lca is not None else right_lca
# Driver program to test above function
# Let us create a binary tree given in the above example
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
print "LCA(4,5) = ", findLCA(root, 4, 5).key
print "LCA(4,6) = ", findLCA(root, 4, 6).key
print "LCA(3,4) = ", findLCA(root, 3, 4).key
print "LCA(2,4) = ", findLCA(root, 2, 4).key
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
LCA(4, 5) = 2
LCA(4, 6) = 1
LCA(3, 4) = 1
LCA(2, 4) = 2
1583
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
v1 is set as true when n1 is present in tree and v2 is set as true if n2 is present in tree.
C++
1584
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
1585
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
{
// Let us create binary tree given in the above example
Node * root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
Node *lca = findLCA(root, 4, 5);
if (lca != NULL)
cout << "LCA(4, 5) = " << lca->key;
else
cout << "Keys are not present ";
lca = findLCA(root, 4, 10);
if (lca != NULL)
cout << "nLCA(4, 10) = " << lca->key;
else
cout << "nKeys are not present ";
return 0;
}
Java
1586
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
// This function returns pointer to LCA of two given
// values n1 and n2.
// v1 is set as true by this function if n1 is found
// v2 is set as true by this function if n2 is found
Node findLCAUtil(Node node, int n1, int n2)
{
// Base case
if (node == null)
return null;
//Store result in temp, in case of key match so that we can search for other key also.
Node temp=null;
// If either n1 or n2 matches with root's key, report the presence
// by setting v1 or v2 as true and return root (Note that if a key
// is ancestor of other, then the ancestor key becomes LCA)
if (node.data == n1)
{
v1 = true;
temp = node;
}
if (node.data == n2)
{
v2 = true;
temp = node;
}
// Look for keys in left and right subtrees
Node left_lca = findLCAUtil(node.left, n1, n2);
Node right_lca = findLCAUtil(node.right, n1, n2);
if (temp != null)
return temp;
// If both of the above calls return Non-NULL, then one key
// is present in once subtree and other is present in other,
// So this node is the LCA
if (left_lca != null && right_lca != null)
return node;
// Otherwise check if left subtree or right subtree is LCA
return (left_lca != null) ? left_lca : right_lca;
}
// Finds lca of n1 and n2 under the subtree rooted with 'node'
Node findLCA(int n1, int n2)
{
1587
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
Python
1588
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
1589
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
1590
Chapter 265. Lowest Common Ancestor in a Binary Tree | Set 1
Output:
LCA(4, 5) = 2
Keys are not present
Source
https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/
1591
Chapter 266
Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer) - GeeksforGeeks
Given values of two nodes in a Binary Tree, find the Lowest Common Ancestor (LCA). It
may be assumed that both nodes exist in the tree.
For example, consider the Binary Tree in diagram, LCA of 10 and 14 is 12 and LCA of 8
and 14 is 8.
Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined
as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to
be a descendant of itself). Source : Wikipedia.
We have discusseddifferent approaches to find LCA in set 1. Finding LCA becomes easy
when parent pointer is given as we can easily find all ancestors of a node using parent
pointer.
1592
Chapter 266. Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
Source
https://www.geeksforgeeks.org/lowest-common-ancestor-in-a-binary-tree-set-2-using-parent-pointer/
1593
Chapter 267
Input : 4 5
Output : 2
Input : 4 7
Output : 1
1594
Chapter 267. Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
The tree given above has dfs traversal in the order: 1-2-4-2-5-2-1-3.
Take another array L[], in which L[i] is the level of node E[i].
And the array H[], which stores the index of first occurrence of ith node in the array E[].
So, for the above tree,
E[] = {1, 2, 4, 2, 5, 2, 1, 3}
L[] = {1, 2, 3, 2, 3, 2, 1, 2}
H[] = {0, 1, 7, 2, 4}
Note that the arrays E and L are with zero-based indexing but the array H has one-based
indexing.
Now, to find the LCA(4, 3), first use the array H and find the indices at which 4 and 3 are
found in E i.e. H[4] and H[3]. So, the indices comes out to be 2 and 7. Now, look at the
subarray L[2 : 7], and find the minimum in this subarray which is 1 (at the 6th index), and
the corresponding element in the array E i.e. E[6] is the LCA(4, 3).
To understand why this works, take LCA(4, 3) again. The path by which one can reach
node 3 from node 4 is the subarray E[2 : 7] . And, if there is a node with lowest level in
this path, then it can simply claimed to be the LCA(4, 3).
Now, the problem is to find the minimum in the subarray E[H[u]….H[v]] (assuming that H[u]
>= H[v]). And, that could be done using segment tree or sparse table. Below is the code
using segment tree.
C++
1595
Chapter 267. Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
1596
Chapter 267. Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
dfs(des);
e.pb(src);
}
}
}
// making the array l
void setting_l(int n) {
for (int i = 0; i < sz(e); i++)
l.pb(level[e[i]]);
}
// making the array h
void setting_h(int n) {
for (int i = 0; i <= n; i++)
h[i] = -1;
for (int i = 0; i < sz(e); i++) {
// if is already stored
if (h[e[i]] == -1)
h[e[i]] = i;
}
}
// Range minimum query to return the index
// of minimum in the subarray L[qs:qe]
int RMQ(int ss, int se, int qs, int qe, int i) {
if (ss > se)
return -1;
// out of range
if (se < qs || qe < ss)
return -1;
// in the range
if (qs <= ss && se <= qe)
return st[i];
int mid = (ss + se) >> 1;
int st = RMQ(ss, mid, qs, qe, left);
int en = RMQ(mid + 1, se, qs, qe, right);
if (st != -1 && en != -1) {
if (l[st] < l[en])
return st;
return en;
} else if (st != -1)
return st;
else if (en != -1)
1597
Chapter 267. Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
return en;
}
// constructs the segment tree
void SegmentTreeConstruction(int ss, int se, int i) {
if (ss > se)
return;
if (ss == se) // leaf
{
st[i] = ss;
return;
}
int mid = (ss + se) >> 1;
SegmentTreeConstruction(ss, mid, left);
SegmentTreeConstruction(mid + 1, se, right);
if (l[st[left]] < l[st[right]])
st[i] = st[left];
else
st[i] = st[right];
}
// Funtion to get LCA
int LCA(int x, int y) {
if (h[x] > h[y])
swap(x, y);
return e[RMQ(0, sz(l) - 1, h[x], h[y], 0)];
}
// Driver code
int main() {
ios::sync_with_stdio(0);
// n=number of nodes in the tree
// q=number of queries to answer
int n = 15, q = 5;
// making the tree
/*
1
/ | \
2 3 4
| \
5 6
/ | \
8 7 9 (right of 5)
/ | \ | \
1598
Chapter 267. Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
10 11 12 13 14
|
15
*/
add_edge(1, 2);
add_edge(1, 3);
add_edge(1, 4);
add_edge(3, 5);
add_edge(4, 6);
add_edge(5, 7);
add_edge(5, 8);
add_edge(5, 9);
add_edge(7, 10);
add_edge(7, 11);
add_edge(7, 12);
add_edge(9, 13);
add_edge(9, 14);
add_edge(12, 15);
level[1] = 1;
leveling(1);
dfs(1);
setting_l(n);
setting_h(n);
SegmentTreeConstruction(0, sz(l) - 1, 0);
cout << LCA(10, 15) << endl;
cout << LCA(11, 14) << endl;
return 0;
}
Output:
7
5
Time Complexity :
The arrays defined are stored in O(n). The segment tree construction also takes O(n) time.
The LCA function calls the function RMQ which takes O(logn) per query (as it uses the
segment tree). So overall time complexity is O(n + q * logn).
1599
Chapter 267. Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
Source
https://www.geeksforgeeks.org/lowest-common-ancestor-in-a-binary-tree-set-3-using-rmq/
1600
Chapter 268
Maximum Consecutive
Increasing Path Length in
Binary Tree
10
/ \
/ \
11 9
/ \ /\
/ \ / \
13 12 13 8
Maximum Consecutive Path Length is 3 (10, 11, 12)
Note: 10, 9 ,8 is NOT considered since
the nodes should be in increasing order.
5
/ \
/ \
8 11
/ \
/ \
9 10
/ /
/ /
1601
Chapter 268. Maximum Consecutive Increasing Path Length in Binary Tree
6 15
Maximum Consecutive Path Length is 2 (8, 9).
Every node in the Binary Tree can either become part of the path which is starting from
one of its parent node or a new path can start from this node itself. The key is to recursively
find the path length for the left and right sub tree and then return the maximum. Some
cases need to be considered while traversing the tree which are discussed below.
prev : stores the value of the parent node. Initialize prev with one less than value of root
node so that the path starting at root can be of length at least 1.
len : Stores the path length which ends at the parent of currently visited node.
Case 1: Value of Current Node is prev +1
In this case increase the path length by 1, and then recursively find the path length for the
left and the right sub tree then return the maximum between two lengths.
Case 2: Value of Current Node is NOT prev+1
A new path can start from this node, so recursively find the path length for the left and the
right sub tree. The path which ends at the parent node of current node might be greater
than the path which starts from this node.So take the maximum of the path which starts
from this node and which ends at previous node.
Below is C++ implementation of above idea.
C++
1602
Chapter 268. Maximum Consecutive Increasing Path Length in Binary Tree
if (!root)
return prev_len;
// Get the value of Current Node
// The value of the current node will be
// prev Node for its left and right children
int cur_val = root->val;
// If current node has to be a part of the
// consecutive path then it should be 1 greater
// than the value of the previous node
if (cur_val == prev_val+1)
{
// a) Find the length of the Left Path
// b) Find the length of the Right Path
// Return the maximum of Left path and Right path
return max(maxPathLenUtil(root->left, cur_val, prev_len+1),
maxPathLenUtil(root->right, cur_val, prev_len+1));
}
// Find length of the maximum path under subtree rooted with this
// node (The path may or may not include this node)
int newPathLen = max(maxPathLenUtil(root->left, cur_val, 1),
maxPathLenUtil(root->right, cur_val, 1));
// Take the maximum previous path and path under subtree rooted
// with this node.
return max(prev_len, newPathLen);
}
// A wrapper over maxPathLenUtil().
int maxConsecutivePathLength(Node *root)
{
// Return 0 if root is NULL
if (root == NULL)
return 0;
// Else compute Maximum Consecutive Increasing Path
// Length using maxPathLenUtil.
return maxPathLenUtil(root, root->val-1, 0);
}
//Driver program to test above function
int main()
{
Node *root = newNode(10);
root->left = newNode(11);
1603
Chapter 268. Maximum Consecutive Increasing Path Length in Binary Tree
root->right = newNode(9);
root->left->left = newNode(13);
root->left->right = newNode(12);
root->right->left = newNode(13);
root->right->right = newNode(8);
cout << "Maximum Consecutive Increasing Path Length is "
<< maxConsecutivePathLength(root);
return 0;
}
Python
1604
Chapter 268. Maximum Consecutive Increasing Path Length in Binary Tree
Output:
Source
https://www.geeksforgeeks.org/maximum-consecutive-increasing-path-length-in-binary-tree/
1605
Chapter 269
1606
Chapter 269. Maximum Path Sum in a Binary Tree
For each node there can be four ways that the max path goes through the node:
1. Node only
2. Max path through Left Child + Node
3. Max path through Right Child + Node
4. Max path through Left Child + Node + Max path through Right Child
The idea is to keep trace of four paths and pick up the max one in the end. An important
thing to note is, root of every subtree need to return maximum path sum such that at most
one child of root is involved. This is needed for parent function call. In below code, this
sum is stored in ‘max_single’ and returned by the recursive function.
C++
1607
Chapter 269. Maximum Path Sum in a Binary Tree
1608
Chapter 269. Maximum Path Sum in a Binary Tree
root->left->left = newNode(20);
root->left->right = newNode(1);
root->right->right = newNode(-25);
root->right->right->left = newNode(3);
root->right->right->right = newNode(4);
cout << "Max path sum is " << findMaxSum(root);
return 0;
}
Java
1609
Chapter 269. Maximum Path Sum in a Binary Tree
1610
Chapter 269. Maximum Path Sum in a Binary Tree
Python
1611
Chapter 269. Maximum Path Sum in a Binary Tree
# Initialize result
findMaxUtil.res = float("-inf")
# Compute and return result
findMaxUtil(root)
return findMaxUtil.res
# Driver program
root = Node(10)
root.left = Node(2)
root.right = Node(10);
root.left.left = Node(20);
root.left.right = Node(1);
root.right.right = Node(-25);
root.right.right.left = Node(3);
root.right.right.right = Node(4);
print "Max path sum is " ,findMaxSum(root);
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Source
https://www.geeksforgeeks.org/find-maximum-path-sum-in-a-binary-tree/
1612
Chapter 270
Maximum difference between node and its ancestor in Binary Tree - GeeksforGeeks
Given a binary tree, we need to find maximum value we can get by subtracting value of
node B from value of node A, where A and B are two nodes of the binary tree and A is an
ancestor of B. Expected time complexity is O(n).
For example, consider below binary tree
We can have various ancestor-node difference, some of which are given below :
8–3=5
1613
Chapter 270. Maximum difference between node and its ancestor in Binary Tree
3 – 7 = -4
8–1=7
10 – 13 = -3
. . . .
But among all those differences maximum value is 7 obtained by subtracting 1 from 8, which
we need to return as result.
As we are given a binary tree, there is no relationship between node values so we need to
traverse whole binary tree to get max difference and we can obtain the result in one traversal
only by following below steps :
If we are at leaf node then just return its value because it can’t be ancestor of any node. Then
at each internal node we will try to get minimum value from left subtree and right subtree
and calculate the difference between node value and this minimum value and according to
that we will update the result.
As we are calculating minimum value while retuning in recurrence we will check all optimal
possibilities (checking node value with minimum subtree value only) of differences and hence
calculate the result in one traversal only.
Below is C++ implementation of above idea.
C++
1614
Chapter 270. Maximum difference between node and its ancestor in Binary Tree
1615
Chapter 270. Maximum difference between node and its ancestor in Binary Tree
int main()
{
// Making above given diagram's binary tree
Node* root;
root = newNode(8);
root->left = newNode(3);
root->left->left = newNode(1);
root->left->right = newNode(6);
root->left->right->left = newNode(4);
root->left->right->right = newNode(7);
root->right = newNode(10);
root->right->right = newNode(14);
root->right->right->left = newNode(13);
printf("Maximum difference between a node and"
" its ancestor is : %d\n", maxDiff(root));
}
Java
1616
Chapter 270. Maximum difference between node and its ancestor in Binary Tree
Node root;
/* Recursive function to calculate maximum ancestor-node
difference in binary tree. It updates value at 'res'
to store the result. The returned value of this function
is minimum value in subtree rooted with 't' */
int maxDiffUtil(Node t, Res res)
{
/* Returning Maximum int value if node is not
there (one child case) */
if (t == null)
return Integer.MAX_VALUE;
/* If leaf node then just return node's value */
if (t.left == null && t.right == null)
return t.key;
/* Recursively calling left and right subtree
for minimum value */
int val = Math.min(maxDiffUtil(t.left, res),
maxDiffUtil(t.right, res));
/* Updating res if (node value - minimum value
from subtree) is bigger than res */
res.r = Math.max(res.r, t.key - val);
/* Returning minimum value got so far */
return Math.min(val, t.key);
}
/* This function mainly calls maxDiffUtil() */
int maxDiff(Node root)
{
// Initialising result with minimum int value
Res res = new Res();
maxDiffUtil(root, res);
return res.r;
}
/* Helper function to print inorder traversal of
binary tree */
void inorder(Node root)
{
if (root != null)
{
inorder(root.left);
System.out.print(root.key + "");
1617
Chapter 270. Maximum difference between node and its ancestor in Binary Tree
inorder(root.right);
}
}
// Driver program to test the above functions
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
// Making above given diagram's binary tree
tree.root = new Node(8);
tree.root.left = new Node(3);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(6);
tree.root.left.right.left = new Node(4);
tree.root.left.right.right = new Node(7);
tree.root.right = new Node(10);
tree.root.right.right = new Node(14);
tree.root.right.right.left = new Node(13);
System.out.println("Maximum difference between a node and"
+ " its ancestor is : " + tree.maxDiff(tree.root));
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output :
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/maximum-difference-between-node-and-its-ancestor-in-binary-tree/
1618
Chapter 271
As we need connected components that have even number of vertices so when we get one
component we can remove the edge that connects it to the remaining tree and we will be left
with a tree with even number of vertices which will be the same problem but of smaller size,
we have to repeat this algorithm until the remaining tree cannot be decomposed further in
the above manner.
We will traverse the tree using DFS which will return the number of vertices in the compo-
nent of which the current node is the root. If a node gets an even number of vertices from
one of its children then the edge from that node to its child will be removed and result will
be increased by one and if the returned number is odd then we will add it to the number of
vertices that the component will have if the current node is the root of it.
1619
Chapter 271. Maximum edge removal from tree to make even forest
1620
Chapter 271. Maximum edge removal from tree to make even forest
Output:
1621
Chapter 271. Maximum edge removal from tree to make even forest
Source
https://www.geeksforgeeks.org/maximum-edge-removal-tree-make-even-forest/
1622
Chapter 272
1623
Chapter 272. Maximum parent children sum in Binary tree
We simply traverse the tree and find the Node that has the maximum sum. We need to
take care of the leaves.
C++
1624
Chapter 272. Maximum parent children sum in Binary tree
root->left->right->left = newNode(44);
root->right = newNode(17);
root->right->left = newNode(7);
root->right->left->right = newNode(11);
root->right->right = newNode(41);
cout << maxSum(root);
return 0;
}
Java
1625
Chapter 272. Maximum parent children sum in Binary tree
return Math.max(res, maxSum(root.right));
}
// Driver code
public static void main (String[] args)
{
Node root = new Node(15);
root.left = new Node(16);
root.left.right = new Node(67);
root.left.right.left = new Node(44);
root.left.left = new Node(8);
root.left.left.left = new Node(55);
root.right = new Node(17);
root.right.right = new Node(41);
root.right.left = new Node(7);
root.right.left.right = new Node(11);
System.out.print(maxSum(root));
}
}
// This code is contributed
// by akash1295
Output:
91
Improved By : akash1295
Source
https://www.geeksforgeeks.org/maximum-parent-children-sum-in-binary-tree/
1626
Chapter 273
1627
Chapter 273. Maximum spiral sum in Binary Tree
1628
Chapter 273. Maximum spiral sum in Binary Tree
1629
Chapter 273. Maximum spiral sum in Binary Tree
Output:
1630
Chapter 273. Maximum spiral sum in Binary Tree
Source
https://www.geeksforgeeks.org/maximum-spiral-sum-in-binary-tree/
1631
Chapter 274
Maximum sum from a tree with adjacent levels not allowed - GeeksforGeeks
Given a binary tree with positive integer values. Find the maximum sum of nodes such that
we cannot pick two levels for computing sum
Examples:
Input : Tree
1
/ \
2 3
/
4
\
5
/
6
Output :11
Explanation: Total items we can take: {1, 4, 6}
or {2, 3, 5}. Max sum = 11.
Input : Tree
1
/ \
2 3
/ / \
4 5 6
/ \ / /
1632
Chapter 274. Maximum sum from a tree with adjacent levels not allowed
17 18 19 30
/ / \
11 12 13
Output :89
Explanation: Total items we can take: {2, 3, 17, 18,
19, 30} or {1, 4, 5, 6, 11, 12, 13}.
Max sum from first set = 89.
Explanation: We know that we need to get item values from alternate tree levels. This
means that if we pick from level 1, the next pick would be from level 3, then level 5 and
so on. Similarly, if we start from level 2, next pick will be from level 4, then level 6 and so
on. So, we actually need to recursively sum all the grandchildren of a particular element as
those are guaranteed to be at the alternate level.
We know for any node of tree, there are 4 grandchildren of it.
grandchild1 = root.left.left;
grandchild2 = root.left.right;
grandchild3 = root.right.left;
grandchild4 = root.right.right;
We can recursively call the getSum() method in the below program to find the sum of these
children and their grandchildren. At the end, we just need to return maximum sum
obtained by starting at level 1 and starting at level 2.
1633
Chapter 274. Maximum sum from a tree with adjacent levels not allowed
{
if (root == null)
return 0;
int sum = root.data;
if (root.left != null) {
sum += getSum(root.left.left);
sum += getSum(root.left.right);
}
if (root.right != null) {
sum += getSum(root.right.left);
sum += getSum(root.right.right);
}
return sum;
}
// Returns maximum sum with adjacent
// levels not allowed. This function
// mainly uses getSumAlternate()
public static int getSum(Node root)
{
if (root == null)
return 0;
// We compute sum of alternate levels
// starting first level and from second
// level.
// And return maximum of two values.
return Math.max(getSumAlternate(root),
(getSumAlternate(root.left) +
getSumAlternate(root.right)));
}
// Driver function
public static void main(String[] args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.right.left = new Node(4);
root.right.left.right = new Node(5);
root.right.left.right.left = new Node(6);
System.out.println(getSum(root));
}
}
Output:
1634
Chapter 274. Maximum sum from a tree with adjacent levels not allowed
11
Source
https://www.geeksforgeeks.org/maximum-sum-tree-adjacent-levels-not-allowed/
1635
Chapter 275
Maximum sum of nodes in Binary tree such that no two are adjacent - GeeksforGeeks
Given a binary tree with a value associated with each node, we need to choose a subset
of these nodes such that sum of chosen nodes is maximum under a constraint that no two
chosen node in subset should be directly connected that is, if we have taken a node in our
sum then we can’t take its any children in consideration and vice versa.
Examples:
Method 1
We can solve this problem by considering the fact that both node and its children can’t be
in sum at same time, so when we take a node into our sum we will call recursively for its
grandchildren or when we don’t take this node we will call for all its children nodes and
finally we will choose maximum from both of these results.
It can be seen easily that above approach can lead to solving same subproblem many times,
for example in above diagram node 1 calls node 4 and 5 when its value is chosen and node
3 also calls them when its value is not chosen so these nodes are processed more than once.
We can stop solving these nodes more than once by memoizing the result at all nodes.
In below code a map is used for memoizing the result which stores result of complete subtree
rooted at a node in the map, so that if it is called again, the value is not calculated again
1636
Chapter 275. Maximum sum of nodes in Binary tree such that no two are adjacent
1637
Chapter 275. Maximum sum of nodes in Binary tree such that no two are adjacent
1638
Chapter 275. Maximum sum of nodes in Binary tree such that no two are adjacent
Output:
11
1639
Chapter 275. Maximum sum of nodes in Binary tree such that no two are adjacent
Output:
21
Source
https://www.geeksforgeeks.org/maximum-sum-nodes-binary-tree-no-two-adjacent/
1640
Chapter 276
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
1641
Chapter 276. Maximum width of a binary tree
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/*Function protoypes*/
int getWidth(struct node* root, int level);
int height(struct node* node);
struct node* newNode(int data);
/* Function to get the maximum width of a binary tree*/
int getMaxWidth(struct node* root)
{
int maxWidth = 0;
int width;
int h = height(root);
int i;
/* Get width of each level and compare
the width with maximum width so far */
1642
Chapter 276. Maximum width of a binary tree
1643
Chapter 276. Maximum width of a binary tree
Java
1644
Chapter 276. Maximum width of a binary tree
1645
Chapter 276. Maximum width of a binary tree
{
if (node == null)
return 0;
else
{
/* compute the height of each subtree */
int lHeight = height(node.left);
int rHeight = height(node.right);
/* use the larger one */
return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1);
}
}
/* Driver program to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
/*
Constructed bunary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
*/
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.right = new Node(8);
tree.root.right.right.left = new Node(6);
tree.root.right.right.right = new Node(7);
System.out.println("Maximum width is " + tree.getMaxWidth(tree.root));
}
}
// This code has been contributed by Mayank Jaiswal
Python
# Python program to find the maximum width of binary tree using Level Order Traversal.
1646
Chapter 276. Maximum width of a binary tree
1647
Chapter 276. Maximum width of a binary tree
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(8)
root.right.right.left = Node(6)
root.right.right.right = Node(7)
"""
Constructed bunary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
"""
print "Maximum width is %d" %(getMaxWidth(root))
# This code is contributed by Naveen Aili
1648
Chapter 276. Maximum width of a binary tree
1649
Chapter 276. Maximum width of a binary tree
Java
1650
Chapter 276. Maximum width of a binary tree
int data;
node left, right;
public node(int data)
{
this.data = data;
}
}
// Function to find the maximum width of
// the tree using level order traversal
static int maxwidth(node root)
{
// Base case
if (root == null)
return 0;
// Initialize result
int maxwidth = 0;
// Do Level order traversal keeping
// track of number of nodes at every level
Queue<node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty())
{
// Get the size of queue when the level order
// traversal for one level finishes
int count = q.size();
// Update the maximum node count value
maxwidth = Math.max(maxwidth, count);
// Iterate for all the nodes in
// the queue currently
while (count-- > 0)
{
// Dequeue an node from queue
node temp = q.remove();
// Enqueue left and right children
// of dequeued node
if (temp.left != null)
{
q.add(temp.left);
}
if (temp.right != null)
{
1651
Chapter 276. Maximum width of a binary tree
q.add(temp.right);
}
}
}
return maxwidth;
}
public static void main(String[] args)
{
node root = new node(1);
root.left = new node(2);
root.right = new node(3);
root.left.left = new node(4);
root.left.right = new node(5);
root.right.right = new node(8);
root.right.right.left = new node(6);
root.right.right.right = new node(7);
/* Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7 */
System.out.println("Maximum width = " + maxwidth(root));
}
}
// This code is contributed by Rishabh Mahrsee
Python
1652
Chapter 276. Maximum width of a binary tree
def getMaxWidth(root):
# base case
if root is None:
return 0
q = []
maxWidth = 0
q.insert(0,root)
while (q != []):
# Get the size of queue when the level order
# traversal for one level finishes
count = len(q)
# Update the maximum node count value
maxWidth = max(count,maxWidth)
while (count is not 0):
count = count-1
temp = q[-1]
q.pop() ;
if temp.left is not None:
q.insert(0,temp.left)
if temp.right is not None:
q.insert(0,temp.right)
return maxWidth
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(8)
root.right.right.left = Node(6)
root.right.right.right = Node(7)
"""
Constructed bunary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
1653
Chapter 276. Maximum width of a binary tree
"""
print "Maximum width is %d" %(getMaxWidth(root))
# This code is contributed by Naveen Aili
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
// A utility function to get height of a binary tree
int height(struct node* node);
// A utility function to allocate a new node with given data
struct node* newNode(int data);
// A utility function that returns maximum value in arr[] of size n
int getMax(int arr[], int n);
// A function that fills count array with count of nodes at every
// level of given binary tree
void getMaxWidthRecur(struct node *root, int count[], int level);
/* Function to get the maximum width of a binary tree*/
int getMaxWidth(struct node* root)
{
int width;
int h = height(root);
// Create an array that will store count of nodes at each level
int *count = (int *)calloc(sizeof(int), h);
1654
Chapter 276. Maximum width of a binary tree
int level = 0;
// Fill the count array using preorder traversal
getMaxWidthRecur(root, count, level);
// Return the maximum value from count array
return getMax(count, h);
}
// A function that fills count array with count of nodes at every
// level of given binary tree
void getMaxWidthRecur(struct node *root, int count[], int level)
{
if(root)
{
count[level]++;
getMaxWidthRecur(root->left, count, level+1);
getMaxWidthRecur(root->right, count, level+1);
}
}
/* UTILITY FUNCTIONS */
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the height of each subtree */
int lHeight = height(node->left);
int rHeight = height(node->right);
/* use the larger one */
return (lHeight > rHeight)? (lHeight+1): (rHeight+1);
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
1655
Chapter 276. Maximum width of a binary tree
node->right = NULL;
return(node);
}
// Return the maximum value from count array
int getMax(int arr[], int n)
{
int max = arr[0];
int i;
for (i = 0; i < n; i++)
{
if (arr[i] > max)
max = arr[i];
}
return max;
}
/* Driver program to test above functions*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(8);
root->right->right->left = newNode(6);
root->right->right->right = newNode(7);
/*
Constructed bunary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
*/
printf("Maximum width is %d \n", getMaxWidth(root));
getchar();
return 0;
}
Java
1656
Chapter 276. Maximum width of a binary tree
1657
Chapter 276. Maximum width of a binary tree
1658
Chapter 276. Maximum width of a binary tree
Python
# Python program to find the maximum width of binary tree using Preorder Traversal.
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to get the maximum width of a binary tree
def getMaxWidth(root):
h = height(root)
# Create an array that will store count of nodes at each level
count = [0] * h
level = 0
# Fill the count array using preorder traversal
getMaxWidthRecur(root, count, level)
# Return the maximum value from count array
return getMax(count,h)
# A function that fills count array with count of nodes at every
# level of given binary tree
def getMaxWidthRecur(root, count, level):
if root is not None:
count[level] += 1
getMaxWidthRecur(root.left, count, level+1)
getMaxWidthRecur(root.right, count, level+1)
1659
Chapter 276. Maximum width of a binary tree
# UTILITY FUNCTIONS
# Compute the "height" of a tree -- the number of
# nodes along the longest path from the root node
# down to the farthest leaf node.
def height(node):
if node is None:
return 0
else:
# compute the height of each subtree
lHeight = height(node.left)
rHeight = height(node.right)
# use the larger one
return (lHeight+1) if (lHeight > rHeight) else (rHeight+1)
# Return the maximum value from count array
def getMax(count, n):
max = count[0]
for i in range (1,n):
if (count[i] > max):
max = count[i]
return max
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(8)
root.right.right.left = Node(6)
root.right.right.right = Node(7)
"""
Constructed bunary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
"""
print "Maximum width is %d" %(getMaxWidth(root))
# This code is contributed by Naveen Aili
1660
Chapter 276. Maximum width of a binary tree
Source
https://www.geeksforgeeks.org/maximum-width-of-a-binary-tree/
1661
Chapter 277
Examples:
The key idea is to build a Segment Tree with a vector at every node and the vector contains
all the elements of the sub-range in a sorted order. And if we observe this segment tree
structure this is somewhat similar to the tree formed during the merge sort algorithm(that
is why it is called merge sort tree)
1662
Chapter 277. Merge Sort Tree for Range Order Statistics
We use same implementation as discussed inMerge Sort Tree (Smaller or equal elements in
given row range)
Firstly, we maintain a vector of pairs where each pair {value, index} is such that first
element of pair represents the element of the input array and the second element of the pair
represents the index at which it occurs.
Now we sort this vector of pairs on the the basis of the first element of each pair.
After this we build a Merge Sort Tree where each node has a vector of indices in the sorted
range.
When we have to answer a query we find if the Kth smallest number lies in the left sub-tree
or in the right sub-tree. The idea is to use two binary searches and find the number of
elements in the left sub-tree such that that the indices lie within the given query range.
Let the number of such indices be M.
If M>=K, it means we will be able to find the Kth smallest Number in the left sub-tree
thus we call on the left sub-tree.
Else the Kth smallest number lies in the right sub-tree but this time we don’t have to look
for the K th smallest number as we already have first M smallest numbers of the range in
the left sub-tree thus we should look for the remaining part ie the (K-M)th number in the
right sub-tree.
This is the Index of Kth smallest number the value at this index is the required number.
1663
Chapter 277. Merge Sort Tree for Range Order Statistics
1664
Chapter 277. Merge Sort Tree for Range Order Statistics
int M = last_in_query_range - first_in_query_range;
if (M >= K) {
// Kth smallest is in left subtree,
// so recursively call left subtree for Kth
// smallest number
return queryRec(segmentStart, mid, queryStart,
queryEnd, 2 * treeIndex, K, tree);
}
else {
// Kth smallest is in right subtree,
// so recursively call right subtree for the
// (K-M)th smallest number
return queryRec(mid + 1, segmentEnd, queryStart,
queryEnd, 2 * treeIndex + 1, K - M, tree);
}
}
// A wrapper over query()
int query(int queryStart, int queryEnd, int K, int n,
vector<pair<int, int> > a, vector<int> tree[])
{
return queryRec(0, n - 1, queryStart - 1, queryEnd - 1,
1, K, tree);
}
// Driver code
int main()
{
int arr[] = { 3, 2, 5, 1, 8, 9 };
int n = sizeof(arr)/sizeof(arr[0]);
// vector of pairs of form {element, index}
vector<pair<int, int> > v;
for (int i = 0; i < n; i++) {
v.push_back(make_pair(arr[i], i));
}
// sort the vector
sort(v.begin(), v.end());
// Construct segment tree in tree[]
vector<int> tree[MAX];
1665
Chapter 277. Merge Sort Tree for Range Order Statistics
buildTree(1, 0, n - 1, v, tree);
// Answer queries
// kSmallestIndex hold the index of the kth smallest number
int kSmallestIndex = query(2, 5, 2, n, v, tree);
cout << arr[kSmallestIndex] << endl;
kSmallestIndex = query(1, 6, 4, n, v, tree);
cout << arr[kSmallestIndex] << endl;
return 0;
}
Output:
2
5
Thus, we can get the Kth smallest number query in range L to R, in O(n(logn)2 ) by building
the merge sort tree on indices.
Source
https://www.geeksforgeeks.org/merge-sort-tree-for-range-order-statistics/
1666
Chapter 278
Merge Two Binary Trees by doing Node Sum (Recursive and Iterative) - GeeksforGeeks
Given two binary trees. We need to merge them into a new binary tree. The merge rule is
that if two nodes overlap, then sum node values up as the new value of the merged node.
Otherwise, the non-null node will be used as the node of new tree.
Example:
Input:
Tree 1 Tree 2
2 3
/ \ / \
1 4 6 1
/ \ \
5 2 7
Note: The merging process must start from the root nodes of both trees.
Recursive Algorithm:
1667
Chapter 278. Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
C++
1668
Chapter 278. Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
1669
Chapter 278. Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
Java
1670
Chapter 278. Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
return t1;
t1.data += t2.data;
t1.left = MergeTrees(t1.left, t2.left);
t1.right = MergeTrees(t1.right, t2.right);
return t1;
}
// Driver method
public static void main(String[] args)
{
/* Let us construct the first Binary Tree
1
/ \
2 3
/ \ \
4 5 6
*/
Node root1 = newNode(1);
root1.left = newNode(2);
root1.right = newNode(3);
root1.left.left = newNode(4);
root1.left.right = newNode(5);
root1.right.right = newNode(6);
/* Let us construct the second Binary Tree
4
/ \
1 7
/ / \
3 2 6 */
Node root2 = newNode(4);
root2.left = newNode(1);
root2.right = newNode(7);
root2.left.left = newNode(3);
root2.right.left = newNode(2);
root2.right.right = newNode(6);
Node root3 = MergeTrees(root1, root2);
System.out.printf("The Merged Binary Tree is:\n");
inorder(root3);
}
}
// This code is contributed by Gaurav Miglani
Output:
1671
Chapter 278. Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
Complexity Analysis:
Iterative Algorithm:
1. Create a stack
2. Push the root nodes of both the trees onto the stack.
3. While the stack is not empty, perform following steps :
(a) Pop a node pair from the top of the stack
(b) For every node pair removed, add the values corresponding to the two nodes and
update the value of the corresponding node in the first tree
(c) If the left child of the first tree exists, push the left child(pair) of both the trees
onto the stack.
(d) If the left child of the first tree doesn’t exist, append the left child of the second
tree to the current node of the first tree
(e) Do same for right child pair as well.
(f) If both the current nodes are NULL, continue with popping the next nodes from
the stack.
4. Return root of updated Tree
1672
Chapter 278. Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
Node *newNode(int data)
{
Node *new_node = new Node;
new_node->data = data;
new_node->left = new_node->right = NULL;
return new_node;
}
/* Given a binary tree, print its nodes in inorder*/
void inorder(Node * node)
{
if (! node)
return;
/* first recur on left child */
inorder(node->left);
/* then print the data of node */
printf("%d ", node->data);
/* now recur on right child */
inorder(node->right);
}
/* Function to merge given two binary trees*/
Node* MergeTrees(Node* t1, Node* t2)
{
if (! t1)
return t2;
if (! t2)
return t1;
stack<snode> s;
snode temp;
temp.l = t1;
temp.r = t2;
s.push(temp);
snode n;
while (! s.empty())
{
n = s.top();
s.pop();
if (n.l == NULL|| n.r == NULL)
continue;
n.l->data += n.r->data;
1673
Chapter 278. Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
1674
Chapter 278. Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
root2->right = newNode(7);
root2->left->left = newNode(3);
root2->right->left = newNode(2);
root2->right->right = newNode(6);
Node *root3 = MergeTrees(root1, root2);
printf("The Merged Binary Tree is:\n");
inorder(root3);
return 0;
}
Output:
Complexity Analysis:
Source
https://www.geeksforgeeks.org/merge-two-binary-trees-node-sum/
1675
Chapter 279
First BST
3
/ \
1 5
Second BST
4
/ \
2 6
Output: 1 2 3 4 5 6
First BST
8
/ \
2 10
/
1
Second BST
5
/
1676
Chapter 279. Merge two BSTs with limited extra space
3
/
0
Output: 0 1 2 3 5 8 10
#include<stdio.h>
#include<stdlib.h>
// Structure of a BST Node
struct node
{
int data;
struct node *left;
struct node *right;
};
//.................... START OF STACK RELATED STUFF....................
// A stack node
struct snode
{
struct node *t;
struct snode *next;
};
// Function to add an elemt k to stack
void push(struct snode **s, struct node *k)
{
struct snode *tmp = (struct snode *) malloc(sizeof(struct snode));
//perform memory check here
tmp->t = k;
tmp->next = *s;
(*s) = tmp;
1677
Chapter 279. Merge two BSTs with limited extra space
}
// Function to pop an element t from stack
struct node *pop(struct snode **s)
{
struct node *t;
struct snode *st;
st=*s;
(*s) = (*s)->next;
t = st->t;
free(st);
return t;
}
// Fucntion to check whether the stack is empty or not
int isEmpty(struct snode *s)
{
if (s == NULL )
return 1;
return 0;
}
//.................... END OF STACK RELATED STUFF....................
/* Utility function to create a new Binary Tree node */
struct node* newNode (int data)
{
struct node *temp = new struct node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
/* A utility function to print Inoder traversal of a Binary Tree */
void inorder(struct node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
// The function to print data of two BSTs in sorted order
void merge(struct node *root1, struct node *root2)
1678
Chapter 279. Merge two BSTs with limited extra space
{
// s1 is stack to hold nodes of first BST
struct snode *s1 = NULL;
// Current node of first BST
struct node *current1 = root1;
// s2 is stack to hold nodes of second BST
struct snode *s2 = NULL;
// Current node of second BST
struct node *current2 = root2;
// If first BST is empty, then output is inorder
// traversal of second BST
if (root1 == NULL)
{
inorder(root2);
return;
}
// If second BST is empty, then output is inorder
// traversal of first BST
if (root2 == NULL)
{
inorder(root1);
return ;
}
// Run the loop while there are nodes not yet printed.
// The nodes may be in stack(explored, but not printed)
// or may be not yet explored
while (current1 != NULL || !isEmpty(s1) ||
current2 != NULL || !isEmpty(s2))
{
// Following steps follow iterative Inorder Traversal
if (current1 != NULL || current2 != NULL )
{
// Reach the leftmost node of both BSTs and push ancestors of
// leftmost nodes to stack s1 and s2 respectively
if (current1 != NULL)
{
push(&s1, current1);
current1 = current1->left;
}
if (current2 != NULL)
{
push(&s2, current2);
current2 = current2->left;
1679
Chapter 279. Merge two BSTs with limited extra space
}
}
else
{
// If we reach a NULL node and either of the stacks is empty,
// then one tree is exhausted, ptint the other tree
if (isEmpty(s1))
{
while (!isEmpty(s2))
{
current2 = pop (&s2);
current2->left = NULL;
inorder(current2);
}
return ;
}
if (isEmpty(s2))
{
while (!isEmpty(s1))
{
current1 = pop (&s1);
current1->left = NULL;
inorder(current1);
}
return ;
}
// Pop an element from both stacks and compare the
// popped elements
current1 = pop(&s1);
current2 = pop(&s2);
// If element of first tree is smaller, then print it
// and push the right subtree. If the element is larger,
// then we push it back to the corresponding stack.
if (current1->data < current2->data)
{
printf("%d ", current1->data);
current1 = current1->right;
push(&s2, current2);
current2 = NULL;
}
else
{
printf("%d ", current2->data);
current2 = current2->right;
push(&s1, current1);
1680
Chapter 279. Merge two BSTs with limited extra space
current1 = NULL;
}
}
}
}
/* Driver program to test above functions */
int main()
{
struct node *root1 = NULL, *root2 = NULL;
/* Let us create the following tree as first tree
3
/ \
1 5
*/
root1 = newNode(3);
root1->left = newNode(1);
root1->right = newNode(5);
/* Let us create the following tree as second tree
4
/ \
2 6
*/
root2 = newNode(4);
root2->left = newNode(2);
root2->right = newNode(6);
// Print sorted nodes of both trees
merge(root1, root2);
return 0;
}
Source
https://www.geeksforgeeks.org/merge-two-bsts-with-limited-extra-space/
1681
Chapter 280
Minimum no. of iterations to pass information to all nodes in the tree - GeeksforGeeks
Given a very large n-ary tree. Where the root node has some information which it wants to
pass to all of its children down to the leaves with the constraint that it can only pass the
information to one of its children at a time (take it as one iteration).
Now in the next iteration the child node can transfer that information to only one of its
children and at the same time instance the child’s parent i.e. root can pass the info to one of
its remaining children. Continuing in this way we have to find the minimum no of iterations
required to pass the information to all nodes in the tree.
Minimum no of iterations for tree below is 6. The root A first passes information to B. In
next iteration, A passes information to E and B passes information to H and so on.
We strongly recommend to minimize the browser and try this yourself first.
1682
Chapter 280. Minimum no. of iterations to pass information to all nodes in the tree
This can be done using Post Order Traversal. The idea is to consider height and children
count on each and every node.
If a child node i takes ci iterations to pass info below its subtree, then its parent will take
(ci + 1) iterations to pass info to subtree rooted at that child i.
If parent has more children, it will pass info to them in subsequent iterations. Let’s say
children of a parent takes c1, c2, c3, c4, …, cn iterations to pass info in their own subtree,
Now parent has to pass info to these n children one by one in n iterations. If parent picks
child i in ith iteration, then parent will take (i + ci) iterations to pass info to child i and all
it’s subtree.
In any iteration, when parent passes info a child i+1, children (1 to i) which got info from
parent already in previous iterations, will pass info to further down in subsequent iterations,
if any child (1 to i) has its own child further down.
To pass info to whole tree in minimum iterations, it needs to be made sure that bandwidth
is utilized as efficiently as possible (i.e. maximum passable no of nodes should pass info
further down in any iteration)
The best possible scenario would be that in nth iteration, n different nodes pass info to their
child.
Nodes with height = 0: (Trivial case) Leaf node has no children (no information passing
needed), so no of iterations would be ZERO.
Nodes with height = 1: Here node has to pass info to all the children one by one (all
children are leaf node, so no more information passing further down). Since all children are
leaf, node can pass info to any child in any order (pick any child who didn’t receive the info
yet). One iteration needed for each child and so no of iterations would be no of children.So
node with height 1 with n children will take n iterations.
Take a counter initialized with ZERO, loop through all children and keep incrementing
counter.
Nodes with height > 1: Let’s assume that there are n children (1 to n) of a node and
minimum no iterations for all n children are c1, c2, …., cn.
To make sure maximum no of nodes participate in info passing in any iteration, parent
should 1st pass info to that child who will take maximum iteration to pass info further
down in subsequent iterations. i.e. in any iteration, parent should choose the child who
takes maximum iteration later on. It can be thought of as a greedy approach where parent
choose that child 1st, who needs maximum no of iterations so that all subsequent iterations
can be utilized efficiently.
If parent goes in any other fashion, then in the end, there could be some nodes which are
done quite early, sitting idle and so bandwidth is not utilized efficiently in further iterations.
If there are two children i and j with minimum iterations ci and cj where ci > cj, then If
parent picks child j 1st then no of iterations needed by parent to pass info to both children
and their subtree would be:max (1 + cj, 2 + ci) = 2 + ci
If parent picks child i 1st then no of iterations needed by parent to pass info to both children
and their subtree would be: max(1 + ci, 2 + cj) = 1 + ci (So picking ci gives better result
than picking cj)
This tells that parent should always choose child i with max ci value in any iteration.
SO here greedy approach is:
sort all ci values decreasing order,
let’s say after sorting, values are c1 > c2 > c3 > …. > cn
take a counter c, set c = 1 + c1 (for child with maximum no of iterations)
1683
Chapter 280. Minimum no. of iterations to pass information to all nodes in the tree
1684
Chapter 280. Minimum no. of iterations to pass information to all nodes in the tree
static int compare(const void * a, const void * b);
};
NAryTree::NAryTree(int N)
{
this->N = N;
adj = new list<int>[N];
}
// To add a child w to v
void NAryTree::addChild(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
/* A recursive function to used by getMinIter(). This function
// mainly does postorder traversal and get minimum iteration of all children
// of node u, sort them in decreasing order and then get minimum iteration
// of node u
1. Get minItr(B) of all children (B) of a node (A)
2. Sort all minItr(B) in descending order
3. Get minItr of A based on all minItr(B)
minItr(A) = child(A) -->> child(A) is children count of node A
For children B from i = 0 to child(A)
minItr(A) = max ( minItr(A), minItr(B) + i + 1)
Base cases would be:
If node is leaf, minItr = 0
If node's height is 1, minItr = children count
*/
void NAryTree::getMinIterUtil(int u, int minItr[])
{
minItr[u] = adj[u].size();
int *minItrTemp = new int[minItr[u]];
int k = 0, tmp = 0;
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for (i = adj[u].begin(); i!= adj[u].end(); ++i)
{
getMinIterUtil(*i, minItr);
minItrTemp[k++] = minItr[*i];
}
qsort(minItrTemp, minItr[u], sizeof (int), compare);
for (k = 0; k < adj[u].size(); k++)
{
1685
Chapter 280. Minimum no. of iterations to pass information to all nodes in the tree
tmp = minItrTemp[k] + k + 1;
minItr[u] = max(minItr[u], tmp);
}
delete[] minItrTemp;
}
// The function to do PostOrder traversal. It uses
// recursive getMinIterUtil()
int NAryTree::getMinIter()
{
// Set minimum iteration all the vertices as zero
int *minItr = new int[N];
int res = -1;
for (int i = 0; i < N; i++)
minItr[i] = 0;
// Start Post Order Traversal from Root
getMinIterUtil(0, minItr);
res = minItr[0];
delete[] minItr;
return res;
}
int NAryTree::compare(const void * a, const void * b)
{
return ( *(int*)b - *(int*)a );
}
// Driver function to test above functions
int main()
{
// TestCase 1
NAryTree tree1(17);
tree1.addChild(0, 1);
tree1.addChild(0, 2);
tree1.addChild(0, 3);
tree1.addChild(0, 4);
tree1.addChild(0, 5);
tree1.addChild(0, 6);
tree1.addChild(1, 7);
tree1.addChild(1, 8);
tree1.addChild(1, 9);
tree1.addChild(4, 10);
tree1.addChild(4, 11);
tree1.addChild(6, 12);
1686
Chapter 280. Minimum no. of iterations to pass information to all nodes in the tree
tree1.addChild(7, 13);
tree1.addChild(7, 14);
tree1.addChild(10, 15);
tree1.addChild(11, 16);
cout << "TestCase 1 - Minimum Iteration: "
<< tree1.getMinIter() << endl;
// TestCase 2
NAryTree tree2(3);
tree2.addChild(0, 1);
tree2.addChild(0, 2);
cout << "TestCase 2 - Minimum Iteration: "
<< tree2.getMinIter() << endl;
// TestCase 3
NAryTree tree3(1);
cout << "TestCase 3 - Minimum Iteration: "
<< tree3.getMinIter() << endl;
// TestCase 4
NAryTree tree4(6);
tree4.addChild(0, 1);
tree4.addChild(1, 2);
tree4.addChild(2, 3);
tree4.addChild(3, 4);
tree4.addChild(4, 5);
cout << "TestCase 4 - Minimum Iteration: "
<< tree4.getMinIter() << endl;
// TestCase 5
NAryTree tree5(6);
tree5.addChild(0, 1);
tree5.addChild(0, 2);
tree5.addChild(2, 3);
tree5.addChild(2, 4);
tree5.addChild(2, 5);
cout << "TestCase 5 - Minimum Iteration: "
<< tree5.getMinIter() << endl;
// TestCase 6
NAryTree tree6(6);
tree6.addChild(0, 1);
tree6.addChild(0, 2);
tree6.addChild(2, 3);
tree6.addChild(2, 4);
tree6.addChild(3, 5);
1687
Chapter 280. Minimum no. of iterations to pass information to all nodes in the tree
1688
Chapter 280. Minimum no. of iterations to pass information to all nodes in the tree
tree9.addChild(1, 7);
tree9.addChild(2, 8);
tree9.addChild(3, 9);
tree9.addChild(4, 10);
tree9.addChild(5, 11);
tree9.addChild(6, 12);
tree9.addChild(7, 13);
tree9.addChild(8, 14);
tree9.addChild(9, 15);
tree9.addChild(10, 16);
tree9.addChild(11, 17);
tree9.addChild(12, 18);
tree9.addChild(13, 19);
tree9.addChild(14, 20);
tree9.addChild(15, 21);
tree9.addChild(16, 22);
tree9.addChild(17, 23);
tree9.addChild(19, 24);
cout << "TestCase 9 - Minimum Iteration: "
<< tree9.getMinIter() << endl;
return 0;
}
Output:
This article is contributed by Anurag Singh. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/minimum-iterations-pass-information-nodes-tree/
1689
Chapter 281
Minimum swap required to convert binary tree to binary search tree - GeeksforGeeks
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index
2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum
number of swap required to convert it into Binary Search Tree.
Examples:
Input : arr[] = { 1, 2, 3 }
Output : 1
Binary tree of the given array:
1690
Chapter 281. Minimum swap required to convert binary tree to binary search tree
The idea is to use the fact that inorder traversal of Binary Search Tree is in increasing order
of their value.
So, find the inorder traversal of the Binary Tree and store it in the array and try to sort the
array. The minimum number of swap required to get the array sorted will be the answer.
Please refer below post to find minimum number of swaps required to get the array sorted.
Minimum number of swaps required to sort an array
Time Complexity: O(n log n).
Exercise: Can we extend this to normal binary tree, i.e., a binary tree represented using
left and right pointers, and not necessarily complete?
Source
https://www.geeksforgeeks.org/minimum-swap-required-convert-binary-tree-binary-search-tree/
1691
Chapter 282
We strongly recommend you to minimize your browser and try this yourself
first.
Node of tree is represented as a key and a variable sized array of children pointers. The
idea is similar to mirror of Binary Tree. For every node, we first recur for all of its children
and then reverse array of children pointers. We can also do these steps in other way, i.e.,
reverse array of children pointers first and then recur for children.
Below is C++ implementation of above idea.
C++
1692
Chapter 282. Mirror of n-ary Tree
// Represents a node of an n-ary tree
struct Node
{
int key;
vector<Node *>child;
};
// Function to convert a tree to its mirror
void mirrorTree(Node * root)
{
// Base case: Nothing to do if root is NULL
if (root==NULL)
return;
// Number of children of root
int n = root->child.size();
// If number of child is less than 2 i.e.
// 0 or 1 we do not need to do anything
if (n < 2)
return;
// Calling mirror function for each child
for (int i=0; i<n; i++)
mirrorTree(root->child[i]);
// Reverse vector (variable sized array) of child
// pointers
reverse(root->child.begin(), root->child.end());
}
// Utility function to create a new tree node
Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
return temp;
}
// Prints the n-ary tree level wise
void printNodeLevelWise(Node * root)
{
if (root==NULL)
return;
// Create a queue and enqueue root to it
queue<Node *>q;
1693
Chapter 282. Mirror of n-ary Tree
q.push(root);
// Do level order traversal. Two loops are used
// to make sure that different levels are printed
// in different lines
while (!q.empty())
{
int n = q.size();
while (n>0)
{
// Dequeue an item from queue and print it
Node * p = q.front();
q.pop();
cout << p->key << " ";
// Enqueue all childrent of the dequeued item
for (int i=0; i<p->child.size(); i++)
q.push(p->child[i]);
n--;
}
cout << endl; // Separator between levels
}
}
// Driver program
int main()
{
/* Let us create below tree
* 10
* / / \ \
* 2 34 56 100
* | / | \
* 1 7 8 9
*/
Node *root = newNode(10);
(root->child).push_back(newNode(2));
(root->child).push_back(newNode(34));
(root->child).push_back(newNode(56));
(root->child).push_back(newNode(100));
(root->child[2]->child).push_back(newNode(1));
(root->child[3]->child).push_back(newNode(7));
(root->child[3]->child).push_back(newNode(8));
(root->child[3]->child).push_back(newNode(9));
cout << "Level order traversal Before Mirroring\n";
printNodeLevelWise(root);
1694
Chapter 282. Mirror of n-ary Tree
mirrorTree(root);
cout << "\nLevel order traversal After Mirroring\n";
printNodeLevelWise(root);
return 0;
}
Python
1695
Chapter 282. Mirror of n-ary Tree
return
# create a queue and enqueue root to it
queue = []
queue.append(root)
# Do level order traversal. Two loops are used
# to make sure that different levels are printed
# in different lines
while(len(queue) >0):
n = len(queue)
while(n > 0) :
# Dequeue an item from queue and print it
p = queue[0]
queue.pop(0)
print p.key,
# Enqueue all children of the dequeued item
for index, value in enumerate(p.child):
queue.append(value)
n -= 1
print "" # Seperator between levels
# Driver Program
""" Let us create below tree
* 10
* / / \ \
* 2 34 56 100
* | / | \
* 1 7 8 9
"""
root = Node(10)
root.child.append(Node(2))
root.child.append(Node(34))
root.child.append(Node(56))
root.child.append(Node(100))
root.child[2].child.append(Node(1))
root.child[3].child.append(Node(7))
root.child[3].child.append(Node(8))
root.child[3].child.append(Node(9))
print "Level order traversal Before Mirroring"
1696
Chapter 282. Mirror of n-ary Tree
printNodeLevelWise(root)
mirrorTree(root)
print "\nLevel Order traversal After Mirroring"
printNodeLevelWise(root)
Output:
Thanks to Nitin Agrawal for providing initial implementation. Please write comments if
you find anything incorrect, or you want to share more information about the topic discussed
above
Source
https://www.geeksforgeeks.org/mirror-of-n-ary-tree/
1697
Chapter 283
Modify a binary tree to get preorder traversal using right pointers only - GeeksforGeeks
Given a binary tree. Modify it in such a way that after modification you can have a preorder
traversal of it using only the right pointers. During modification, you can use right as well
as left pointers.
Examples:
Input : 10
/ \
8 2
/ \
3 5
Output : 10
\
8
\
3
\
5
\
2
Explanation : The preorder traversal
of given binary tree is 10 8 3 5 2.
Method 1 (Recursive)
One needs to make the right pointer of root point to the left subtree.
1698
Chapter 283. Modify a binary tree to get preorder traversal using right pointers only
If the node has just left child, then just moving the child to right will complete the processing
for that node.
If there is a right child too, then it should be made right child of the right-most of the
original left subtree.
The above function used in the code process a node and then returns the rightmost node of
the transformed subtree.
C++
1699
Chapter 283. Modify a binary tree to get preorder traversal using right pointers only
rightMost = modifytree(root->left);
// set root right to left subtree
root->right = root->left;
root->left = NULL;
}
// if the right subtree does
// not exists we are done!
if (!right)
return rightMost;
// set right pointer of right-most
// of the original left subtree
rightMost->right = right;
// modify the rightsubtree
rightMost = modifytree(right);
return rightMost;
}
// printing using right pointer only
void printpre(struct Node* root)
{
while (root != NULL) {
cout << root->data << " ";
root = root->right;
}
}
// Driver program to test above functions
int main()
{
/* Constructed binary tree is
10
/ \
8 2
/ \
3 5 */
struct Node* root = newNode(10);
root->left = newNode(8);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
modifytree(root);
printpre(root);
1700
Chapter 283. Modify a binary tree to get preorder traversal using right pointers only
return 0;
}
Output:
10 8 3 5 2
Method 2 (Iterative)
This can be easily done using iterative preorder traversal. See here. Iterative preorder
traversal
The idea is to maintain a variable prev which maintains the previous node of the preorder
traversal. Every-time a new node is encountered, the node set its right to previous one and
prev is made equal to the current node. In the end we will have a sort of linked list whose
first element is root then left child then right, so on and so forth.
C++
1701
Chapter 283. Modify a binary tree to get preorder traversal using right pointers only
1702
Chapter 283. Modify a binary tree to get preorder traversal using right pointers only
{
while (root != NULL) {
cout << root->data << " ";
root = root->right;
}
}
// Driver code
int main()
{
/* Constructed binary tree is
10
/ \
8 2
/ \
3 5
*/
struct Node* root = newNode(10);
root->left = newNode(8);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
modifytree(root);
printpre(root);
return 0;
}
Output:
10 8 3 5 2
Improved By : 02DCE
Source
https://www.geeksforgeeks.org/modify-binary-tree-get-preorder-traversal-using-right-pointers/
1703
Chapter 284
1704
Chapter 284. Morris traversal for Preorder
1705
Chapter 284. Morris traversal for Preorder
Java
1706
Chapter 284. Morris traversal for Preorder
}
}
class BinaryTree {
Node root;
void morrisTraversalPreorder()
{
morrisTraversalPreorder(root);
}
// Preorder traversal without recursion and without stack
void morrisTraversalPreorder(Node node) {
while (node != null) {
// If left child is null, print the current node data. Move to
// right child.
if (node.left == null) {
System.out.print(node.data + " ");
node = node.right;
} else {
// Find inorder predecessor
Node current = node.left;
while (current.right != null && current.right != node) {
current = current.right;
}
// If the right child of inorder predecessor already points to
// this node
if (current.right == node) {
current.right = null;
node = node.right;
}
// If right child doesn't point to this node, then print this
// node and make right child point to this node
else {
System.out.print(node.data + " ");
current.right = node;
node = node.left;
}
}
}
}
void preorder()
1707
Chapter 284. Morris traversal for Preorder
{
preorder(root);
}
// Function for Standard preorder traversal
void preorder(Node node) {
if (node != null) {
System.out.print(node.data + " ");
preorder(node.left);
preorder(node.right);
}
}
// Driver programs to test above functions
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.left.left.left = new Node(8);
tree.root.left.left.right = new Node(9);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(11);
tree.morrisTraversalPreorder();
System.out.println("");
tree.preorder();
}
}
// this code has been contributed by Mayank Jaiswal
Python3
1708
Chapter 284. Morris traversal for Preorder
1709
Chapter 284. Morris traversal for Preorder
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left= Node(6)
root.right.right = Node(7)
root.left.left.left = Node(8)
root.left.left.right = Node(9)
root.left.right.left = Node(10)
root.left.right.right = Node(11)
MorrisTraversal(root)
print("\n")
preorfer(root)
# This code is contributed by 'Aartee'
Output:
1 2 4 8 9 5 10 11 3 6 7
1 2 4 8 9 5 10 11 3 6 7
Limitations:
Morris traversal modifies the tree during the process. It establishes the right links while
moving down the tree and resets the right links while moving up the tree. So the algorithm
cannot be applied if write operations are not allowed.
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please
write comments if you find anything incorrect, or you want to share more information about
the topic discussed above.
Source
https://www.geeksforgeeks.org/morris-traversal-for-preorder/
1710
Chapter 285
1711
Chapter 285. Next Larger element in n-ary tree
return temp;
}
void nextLargerElementUtil(Node* root, int x, Node** res)
{
if (root == NULL)
return;
// if root is less than res but greater than
// x update res
if (root->key > x)
if (!(*res) || (*res)->key > root->key)
*res = root;
// Number of children of root
int numChildren = root->child.size();
// Recur calling for every child
for (int i = 0; i < numChildren; i++)
nextLargerElementUtil(root->child[i], x, res);
return;
}
// Function to find next Greater element of x in tree
Node* nextLargerElement(Node* root, int x)
{
// resultant node
Node* res = NULL;
// calling helper function
nextLargerElementUtil(root, x, &res);
return res;
}
// Driver program
int main()
{
/* Let us create below tree
* 5
* / | \
* 1 2 3
* / / \ \
* 15 4 5 6
*/
Node* root = newNode(5);
1712
Chapter 285. Next Larger element in n-ary tree
(root->child).push_back(newNode(1));
(root->child).push_back(newNode(2));
(root->child).push_back(newNode(3));
(root->child[0]->child).push_back(newNode(15));
(root->child[1]->child).push_back(newNode(4));
(root->child[1]->child).push_back(newNode(5));
(root->child[2]->child).push_back(newNode(6));
int x = 5;
cout << "Next larger element of " << x << " is ";
cout << nextLargerElement(root, x)->key << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/next-larger-element-n-ary-tree/
1713
Chapter 286
Node having maximum sum of immediate children and itself in n-ary tree - GeeksforGeeks
Given an N-Ary tree, find and return the node for which sum of data of all children and
the node itself is maximum. In the sum, data of node itself and data of its immediate
children is to be taken.
For example in the given tree,
1714
Chapter 286. Node having maximum sum of immediate children and itself in n-ary tree
1715
Chapter 286. Node having maximum sum of immediate children and itself in n-ary tree
1716
Chapter 286. Node having maximum sum of immediate children and itself in n-ary tree
int maxsum = 0;
maxSumUtil(root, &resNode, &maxsum);
// return the key of resultant node
return resNode->key;
}
// Driver program
int main()
{
/* Let us create below tree
* 1
* / | \
* 2 3 4
* / \ / | \ \
* 5 6 7 8 9 10
*/
Node* root = newNode(1);
(root->child).push_back(newNode(2));
(root->child).push_back(newNode(3));
(root->child).push_back(newNode(4));
(root->child[0]->child).push_back(newNode(5));
(root->child[0]->child).push_back(newNode(6));
(root->child[2]->child).push_back(newNode(5));
(root->child[2]->child).push_back(newNode(6));
(root->child[2]->child).push_back(newNode(6));
cout << maxSum(root) << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/node-maximum-sum-immediate-children-n-ary-tree/
1717
Chapter 287
1718
Chapter 287. Non-recursive program to delete an entire binary tree
return;
// Create an empty queue for level order traversal
queue<Node *> q;
// Do level order traversal starting from root
q.push(root);
while (!q.empty())
{
Node *node = q.front();
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
free(node);
}
}
/* Deletes a tree and sets the root as NULL */
void deleteTree(Node** node_ref)
{
_deleteTree(*node_ref);
*node_ref = NULL;
}
// Utility function to create a new tree Node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// create a binary tree
Node *root = newNode(15);
root->left = newNode(10);
root->right = newNode(20);
root->left->left = newNode(8);
root->left->right = newNode(12);
root->right->left = newNode(16);
1719
Chapter 287. Non-recursive program to delete an entire binary tree
root->right->right = newNode(25);
//delete entire binary tree
deleteTree(&root);
return 0;
}
Java
1720
Chapter 287. Non-recursive program to delete an entire binary tree
q.add(node.left);
if (node.right != null)
q.add(node.right);
}
}
/* Deletes a tree and sets the root as NULL */
void deleteTree()
{
_deleteTree();
root = null;
}
// Driver program to test above functions
public static void main(String[] args)
{
// create a binary tree
BinaryTree tree = new BinaryTree();
tree.root = new Node(15);
tree.root.left = new Node(10);
tree.root.right = new Node(20);
tree.root.left.left = new Node(8);
tree.root.left.right = new Node(12);
tree.root.right.left = new Node(16);
tree.root.right.right = new Node(25);
// delete entire binary tree
tree.deleteTree();
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Python
1721
Chapter 287. Non-recursive program to delete an entire binary tree
def _deleteTree(root):
# Base Case
if root is None:
return
# Create a empty queue for level order traversal
q = []
# Do level order traversal starting from root
q.append(root)
while(len(q)>0):
node = q.pop(0)
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
node = None
return node
# Deletes a tree and sets the root as None
def deleteTree(node_ref):
node_ref = _deleteTree(node_ref)
return node_ref
# Driver program to test above function
# Create a binary tree
root = Node(15)
root.left = Node(10)
root.right = Node(20)
root.left.left = Node(8)
root.left.right = Node(12)
root.right.left = Node(16)
root.right.right = Node(25)
# delete entire binary tree
root = deleteTree(root)
# This program is contributed by Nikhil Kumar Singh(nickzuck_007)
1722
Chapter 287. Non-recursive program to delete an entire binary tree
Source
https://www.geeksforgeeks.org/non-recursive-program-to-delete-an-entire-binary-tree/
1723
Chapter 288
Input : n = 1
Output : 1
Input : n = 2
Output : 2
Input : n = 3
Output : 5
Background :
In Preorder traversal, we process the root node first, then traverse the left child node and
then right child node.
For example preorder traversal of below tree is 1 2 4 5 3 6 7
1724
Chapter 288. Number of Binary Trees for given Preorder Sequence length
• Assume there is only 1 node (that is 2 in this case), So only 1 Binary tree is Possible
• Now, assume there are 2 nodes (namely 2 and 4), So only 2 Binary Tree are Possible:
• Now, when there are 3 nodes (namely 2, 4 and 6), So Possible Binary tree are 5
• Consider 4 nodes (that are 2, 4, 6 and 8), So Possible Binary Tree are 14.
Let’s say BT(1) denotes number of Binary tree for 1 node. (We assume BT(0)=1)
BT(4) = BT(0) * BT(3) + BT(1) * BT(2) + BT(2) * BT(1) + BT(3) * BT(0)
BT(4) = 1 * 5 + 1 * 2 + 2 * 1 + 5 * 1 = 14
• Similarly, considering all the 5 nodes (2, 4, 6, 8 and 10). Possible number of Binary
Tree are:
BT(5) = BT(0) * BT(4) + BT(1) * BT(3) + BT(2) * BT(2) + BT(3) * BT(1) +
BT(4) * BT(0)
BT(5) = 1 * 14 + 1 * 5 + 2 * 2 + 5 * 1 + 14 * 1 = 42
1725
Chapter 288. Number of Binary Trees for given Preorder Sequence length
1726
Chapter 288. Number of Binary Trees for given Preorder Sequence length
Java
1727
Chapter 288. Number of Binary Trees for given Preorder Sequence length
{
int n = 5;
System.out.println("Total Possible " +
"Binary Tree are : " +
countTrees(n));
}
}
// This code is contributed by anuj_67.
Output:
Alternative :
This can also be done using Catalan number Cn = (2n)!/(n+1)!*n!
For n = 0, 1, 2, 3, … values of Catalan numbers are 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862,
…. So are numbers of Binary Search Trees.
Improved By : vt_m
Source
https://www.geeksforgeeks.org/number-of-binary-trees-for-given-preorder-sequence-length/
1728
Chapter 289
Example :
Input : x = 50
1729
Chapter 289. Number of children of given node in n-ary Tree
Output : 3
Explanation : 50 has 3 children having values 40, 100 and 20.
Approach :
1730
Chapter 289. Number of children of given node in n-ary Tree
int n = q.size();
// If this node has children
while (n > 0) {
// Dequeue an item from queue and
// check if it is equal to x
// If YES, then return number of children
Node* p = q.front();
q.pop();
if (p->key == x) {
numChildren = numChildren + p->child.size();
return numChildren;
}
// Enqueue all children of the dequeued item
for (int i = 0; i < p->child.size(); i++)
q.push(p->child[i]);
n--;
}
}
return numChildren;
}
// Driver program
int main()
{
// Creating a generic tree
Node* root = new Node(20);
(root->child).push_back(new Node(2));
(root->child).push_back(new Node(34));
(root->child).push_back(new Node(50));
(root->child).push_back(new Node(60));
(root->child).push_back(new Node(70));
(root->child[0]->child).push_back(new Node(15));
(root->child[0]->child).push_back(new Node(20));
(root->child[1]->child).push_back(new Node(30));
(root->child[2]->child).push_back(new Node(40));
(root->child[2]->child).push_back(new Node(100));
(root->child[2]->child).push_back(new Node(20));
(root->child[0]->child[1]->child).push_back(new Node(25));
(root->child[0]->child[1]->child).push_back(new Node(50));
// Node whose number of
// children is to be calculated
int x = 50;
// Function calling
1731
Chapter 289. Number of children of given node in n-ary Tree
Output:
Source
https://www.geeksforgeeks.org/number-children-given-node-n-ary-tree/
1732
Chapter 290
Number of full binary trees such that each node is product of its children - GeeksforGeeks
Given an array of n integers, each integer is greater than 1. The task is to find the number
of Full binary tree from the given integers, such that each non-node leaf node value is the
product of its children value. Given that, each integer can be used multiple times in a full
binary tree.
Examples:
Input : arr[] = { 2, 3, 4, 6 }.
Output : 7
There can be 7 full binary tree with the given product property.
6 ,
/ \
2 3
6
/ \
1733
Chapter 290. Number of full binary trees such that each node is product of its children
3 2
We find maximum value in given array and create an array to store presence of elements in
this array. The idea is, for all multiples of each integer less than the maximum value of the
array, try to make full binary tree if the multiple is present in the array.
Observe that for any full binary tree with given property, the smaller values will always be
at the last level. So, try to find the number of such full binary tree from the minimum value
of the array to maximum value of the array.
Algorithm to solve the problem:
1. Initialize possible number of such full binary tree for each element equal to 1. Since
single node also contribute to the answer.
2. For each element of the array, arr[i], from minimum value to maximum value of array.
……a) For each multiple of arr[i], find if multiple is present or not.
……b) If yes, then the number of such possible full binary tree for multiple of arr[i], say m,
is equal to the product of the number of such possible full binary tree of arr[i] and number
of such possible full binary tree of arr[i]/m.
C++
1734
Chapter 290. Number of full binary trees such that each node is product of its children
1735
Chapter 290. Number of full binary trees such that each node is product of its children
{
int arr[] = { 2, 3, 4, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
cout << numoffbt(arr, n) << endl;
return 0;
}
Java
1736
Chapter 290. Number of full binary trees such that each node is product of its children
// From minimum value to maximum value of array
// finding the number of all possible Full
// Binary Trees.
int ans = 0;
for (int i = minvalue; i <= maxvalue; i++)
{
// Find if value present in the array
if (mark[i] != 0)
{
// For each multiple of i, less than
// equal to maximum value of array
for (int j = i + i;
j <= maxvalue && j/i <= i; j += i)
{
// If multiple is not present in
// the array then continue.
if (mark[j] == 0)
continue;
// Finding the number of possible
// Full binary trees for multiple
// j by multiplying number of
// possible Full binary tree from
// the number i and number of
// possible Full binary tree from i/j.
value[j] = value[j] + (value[i]
* value[j/i]);
// Condition for possiblity when
// left chid became right child
// and vice versa.
if (i != j / i)
value[j] = value[j] + (value[i]
* value[j/i]);
}
}
ans += value[i];
}
return ans;
}
//driver code
public static void main (String[] args)
{
1737
Chapter 290. Number of full binary trees such that each node is product of its children
int arr[] = { 2, 3, 4, 6 };
int n = arr.length;
System.out.print(numoffbt(arr, n));
}
}
//This code is contributed by Anant Agarwal.
Python3
# Python3 program to find number of
# full binary tree such that each node
# is product of its children.
# Return the number of all possible full
# binary tree with given product propert.
def numoffbt(arr, n):
# Finding the minimum and maximum
# values in given array.
maxvalue = -2147483647
minvalue = 2147483647
for i in range(n):
maxvalue = max(maxvalue, arr[i])
minvalue = min(minvalue, arr[i])
mark = [0 for i in range(maxvalue + 2)]
value = [0 for i in range(maxvalue + 2)]
# Marking the presence of each array element
# and initialising the number of possible
# full binary tree for each integer equal
# to 1 because single node will also
# contribute as a full binary tree.
for i in range(n):
mark[arr[i]] = 1
value[arr[i]] = 1
# From minimum value to maximum value
# of array finding the number of all
# possible Full Binary Trees.
ans = 0
1738
Chapter 290. Number of full binary trees such that each node is product of its children
C#
1739
Chapter 290. Number of full binary trees such that each node is product of its children
class GFG
{
// Return the number of all possible full binary
// tree with given product propert.
static int numoffbt(int []arr, int n)
{
// Finding the minimum and maximum values in
// given array.
int maxvalue = -2147483647, minvalue = 2147483647;
for (int i = 0; i < n; i++)
{
maxvalue = Math.Max(maxvalue, arr[i]);
minvalue = Math.Min(minvalue, arr[i]);
}
int []mark=new int[maxvalue + 2];
int []value=new int[maxvalue + 2];
for(int i = 0;i < maxvalue + 2; i++)
{
mark[i]=0;
value[i]=0;
}
// Marking the presence of each array element
// and initialising the number of possible
// full binary tree for each integer equal
// to 1 because single node will also
// contribute as a full binary tree.
for (int i = 0; i < n; i++)
{
mark[arr[i]] = 1;
value[arr[i]] = 1;
}
// From minimum value to maximum value of array
// finding the number of all possible Full
// Binary Trees.
int ans = 0;
for (int i = minvalue; i <= maxvalue; i++)
{
// Find if value present in the array
if (mark[i] != 0)
{
// For each multiple of i, less than
// equal to maximum value of array
for (int j = i + i;
j <= maxvalue && j/i <= i; j += i)
1740
Chapter 290. Number of full binary trees such that each node is product of its children
{
// If multiple is not present in the
// array then continue.
if (mark[j] == 0)
continue;
// Finding the number of possible Full
// binary trees for multiple j by
// multiplying number of possible Full
// binary tree from the number i and
// number of possible Full binary tree
// from i/j.
value[j] = value[j] + (value[i] * value[j/i]);
// Condition for possiblity when left
// chid became right child and vice versa.
if (i != j/i)
value[j] = value[j] + (value[i] * value[j/i]);
}
}
ans += value[i];
}
return ans;
}
// Driver code
public static void Main()
{
int []arr = { 2, 3, 4, 6 };
int n = arr.Length;
Console.Write(numoffbt(arr, n));
}
}
// This code is contributed by Anant Agarwal.
Output:
Source
https://www.geeksforgeeks.org/number-full-binary-trees-node-product-children/
1741
Chapter 291
Approach :
The idea is maintain a count variable initialize to 0. Traverse the tree and compare root
data with x. If root data is greater than x, increment the count variable and recursively call
for all its children.
Below is the implementation of idea.
1742
Chapter 291. Number of nodes greater than a given value in n-ary tree
};
// Utility function to create
// a new tree node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
return temp;
}
// Function to find nuber of nodes
// gretaer than x
int nodesGreaterThanX(Node* root, int x)
{
if (root == NULL)
return 0;
int count = 0;
// if current root is greater
// than x increment count
if (root->key > x)
count++;
// Number of children of root
int numChildren = root->child.size();
// recursively calling for every child
for (int i = 0; i < numChildren; i++) {
Node* child = root->child[i];
count += nodesGreaterThanX(child, x);
}
// return the count
return count;
}
// Driver program
int main()
{
/* Let us create below tree
* 5
* / | \
* 1 2 3
* / / \ \
* 15 4 5 6
*/
1743
Chapter 291. Number of nodes greater than a given value in n-ary tree
Node* root = newNode(5);
(root->child).push_back(newNode(1));
(root->child).push_back(newNode(2));
(root->child).push_back(newNode(3));
(root->child[0]->child).push_back(newNode(15));
(root->child[1]->child).push_back(newNode(4));
(root->child[1]->child).push_back(newNode(5));
(root->child[2]->child).push_back(newNode(6));
int x = 5;
cout << "Number of nodes greater than "
<< x << " are ";
cout << nodesGreaterThanX(root, x)
<< endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/number-nodes-greater-given-value-n-ary-tree/
1744
Chapter 292
Example :
Input : 30
Output : 3
1745
Chapter 292. Number of siblings of a given Node in n-ary Tree
Approach : For every node in the given n-ary tree, push the children of the current node
in the queue. While adding the children of current node in queue, check if any children is
equal to the given value x or not. If yes, then return the number of siblings of x.
Below is the implementation of the above idea :
1746
Chapter 292. Number of siblings of a given Node in n-ary Tree
1747
Chapter 292. Number of siblings of a given Node in n-ary Tree
Output:
Source
https://www.geeksforgeeks.org/number-siblings-given-node-n-ary-tree/
1748
Chapter 293
Input : 2
/ \
1 3
/ \ / \
4 10 8 5
/
6
Output : 6
The subtrees are 4, 6, 1, 8, 3
/ \ / \
4 10 8 5
/
6
2
/ \
1 3
/ \ / \
4 10 8 5
/
6
The idea is to recursively traverse the tree. For every node, recursively count even numbers
1749
Chapter 293. Number of subtrees having odd count of even numbers
in left and right subtrees. If root is also even, then add it also to count. If count becomes
odd, increment result.
int countSubtrees(root)
{
if (root == NULL)
return 0;
1750
Chapter 293. Number of subtrees having odd count of even numbers
node->data = data;
node->left = node->right = NULL;
return(node);
}
// Returns count of subtrees having odd count of
// even numbers
int countRec(struct Node* root, int *pcount)
{
// base condition
if (root == NULL)
return 0;
// count even nodes in left subtree
int c = countRec(root->left, pcount);
// Add even nodes in right subtree
c += countRec(root->right, pcount);
// Check if root data is an even number
if (root->data % 2 == 0)
c += 1;
// if total count of even numbers
// for the subtree is odd
if (c % 2 != 0)
(*pcount)++;
// Total count of even nodes of the subtree
return c;
}
// A wrapper over countRec()
int countSubtrees(Node *root)
{
int count = 0;
int *pcount = &count;
countRec(root, pcount);
return count;
}
// Driver program to test above
int main()
{
// binary tree formation
struct Node *root = newNode(2); /* 2 */
root->left = newNode(1); /* / \ */
root->right = newNode(3); /* 1 3 */
1751
Chapter 293. Number of subtrees having odd count of even numbers
Output:
Count = 6
Source
https://www.geeksforgeeks.org/number-subtrees-odd-count-even-numbers/
1752
Chapter 294
Number of turns to reach from one node to other in binary tree - GeeksforGeeks
Given a binary tree and two nodes. The task is to count the number of turns needs to reach
from one node to another node of the Binary tree.
Examples:
1753
Chapter 294. Number of turns to reach from one node to other in binary tree
Case 1:
If none of the nodes is equal to
LCA, we get these nodes either on
the left side or right side.
We call two functions for each node.
....a) if (CountTurn(LCA->right, first,
false, &Count)
|| CountTurn(LCA->left, first,
true, &Count)) ;
....b) Same for second node.
....Here Count is used to store number of
turns need to reached the target node.
Case 2:
If one of the nodes is equal to LCA_Node.
Then we count only number of turns needs
to reached the second node.
If LCA == (Either first or second)
....a) if (countTurn(LCA->right, second/first,
false, &Count)
|| countTurn(LCA->left, second/first,
true, &Count)) ;
1754
Chapter 294. Number of turns to reach from one node to other in binary tree
C++
1755
Chapter 294. Number of turns to reach from one node to other in binary tree
1756
Chapter 294. Number of turns to reach from one node to other in binary tree
// Function to find nodes common to given two nodes
int NumberOFTurn(struct Node* root, int first,
int second)
{
struct Node* LCA = findLCA(root, first, second);
// there is no path between these two node
if (LCA == NULL)
return -1;
int Count = 0;
// case 1:
if (LCA->key != first && LCA->key != second) {
// count number of turns needs to reached
// the second node from LCA
if (CountTurn(LCA->right, second, false,
&Count)
|| CountTurn(LCA->left, second, true,
&Count))
;
// count number of turns needs to reached
// the first node from LCA
if (CountTurn(LCA->left, first, true,
&Count)
|| CountTurn(LCA->right, first, false,
&Count))
;
return Count + 1;
}
// case 2:
if (LCA->key == first) {
// count number of turns needs to reached
// the second node from LCA
CountTurn(LCA->right, second, false, &Count);
CountTurn(LCA->left, second, true, &Count);
return Count;
} else {
// count number of turns needs to reached
// the first node from LCA1
CountTurn(LCA->right, first, false, &Count);
CountTurn(LCA->left, first, true, &Count);
return Count;
1757
Chapter 294. Number of turns to reach from one node to other in binary tree
}
}
// Driver program to test above functions
int main()
{
// Let us create binary tree given in the above
// example
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->right->left->left = newNode(9);
root->right->left->right = newNode(10);
int turn = 0;
if ((turn = NumberOFTurn(root, 5, 10)))
cout << turn << endl;
else
cout << "Not Possible" << endl;
return 0;
}
Java
1758
Chapter 294. Number of turns to reach from one node to other in binary tree
}
}
// Utility function to find the LCA of
// two given values n1 and n2.
static Node findLCA(Node root, int n1, int n2) {
// Base case
if (root == null)
return null;
// If either n1 or n2 matches with
// root's key, report the presence by
// returning root (Note that if a key
// is ancestor of other, then the
// ancestor key becomes LCA
if (root.key == n1 || root.key == n2)
return root;
// Look for keys in left and right subtrees
Node left_lca = findLCA(root.left, n1, n2);
Node right_lca = findLCA(root.right, n1, n2);
// If both of the above calls return
// Non-NULL, then one key is present
// in once subtree and other is present
// in other, So this node is the LCA
if (left_lca != null && right_lca != null)
return root;
// Otherwise check if left subtree or right
// subtree is LCA
return (left_lca != null) ? left_lca : right_lca;
}
// function count number of turn need to reach
// given node from it's LCA we have two way to
static boolean CountTurn(Node root, int key, boolean turn) {
if (root == null)
return false;
// if found the key value in tree
if (root.key == key)
return true;
// Case 1:
if (turn == true) {
if (CountTurn(root.left, key, turn))
return true;
1759
Chapter 294. Number of turns to reach from one node to other in binary tree
1760
Chapter 294. Number of turns to reach from one node to other in binary tree
Output:
Source
https://www.geeksforgeeks.org/number-turns-reach-one-node-binary-tree/
1761
Chapter 295
Now we have to find the number of ways of traversing the whole tree starting from the root
vertex. There can be many such ways. Some of them are listed below.
1) N->M->K->J->B->F->D->E->C->H->I->L->A (kind-of depth first traversal).
2) A->B->F->D->E->K->J->G->C->H->I->N->M->L (level order traversal)
3) ………
1762
Chapter 295. Number of ways to traverse an N-ary tree
4) ………
.
.
.
and so on….
We strongly recommend you to minimize your browser and try this yourself
first.
The count of all ways to traverse is the product of factorials of the number of children of
each node. Refer to the below figure for clear understanding-
Here,
‘A’ has four children, so 4! permutations possible
‘B’ has two children, so 2! permutations possible
‘F’ has no children, so 0! permutations possible
…..
And so on
Hence all such ways are- 4 ! * 2 ! * 0 ! * 1 ! * 3 ! * 2 ! * 0 ! * 0 ! * 0 ! * 0 ! * 1 ! * 0 ! * 0
! = 576 way
That’s a huge number of ways and among them only few proves to be useful, like- inorder,
level-order, preorder, postorder (arranged according to the popularity of these traversals)
1763
Chapter 295. Number of ways to traverse an N-ary tree
{
char key;
vector<Node *> child;
};
// Utility function to create a new tree node
Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
return temp;
}
// Untility Function to find factorial of given number
int factorial(int n)
{
if (n == 0)
return 1;
return n*factorial(n-1);
}
// Function to calculate the number of ways of travesing
// the n-ary starting from root.
// This function is just a modified breadth-first search.
// We can use a depth-first search too.
int calculateWays(Node * root)
{
int ways = 1; // Initialize result
// If the tree is empty there is no way of traversing
// the tree.
if (root == NULL)
return 0;
// Create a queue and enqueue root to it.
queue<Node *>q;
q.push(root);
// Level order traversal.
while (!q.empty())
{
// Dequeue an item from queue and print it
Node * p = q.front();
q.pop();
// The number of ways is the product of
// factorials of number of children of each node.
ways = ways*(factorial(p->child.size()));
1764
Chapter 295. Number of ways to traverse an N-ary tree
// Enqueue all childrent of the dequeued item
for (int i=0; i<p->child.size(); i++)
q.push(p->child[i]);
}
return(ways);
}
// Driver program
int main()
{
/* Let us create below tree
* A
* / / \ \
* B F D E
* / \ | /|\
* K J G C H I
* /\ \
* N M L
*/
Node *root = newNode('A');
(root->child).push_back(newNode('B'));
(root->child).push_back(newNode('F'));
(root->child).push_back(newNode('D'));
(root->child).push_back(newNode('E'));
(root->child[0]->child).push_back(newNode('K'));
(root->child[0]->child).push_back(newNode('J'));
(root->child[2]->child).push_back(newNode('G'));
(root->child[3]->child).push_back(newNode('C'));
(root->child[3]->child).push_back(newNode('H'));
(root->child[3]->child).push_back(newNode('I'));
(root->child[0]->child[0]->child).push_back(newNode('N'));
(root->child[0]->child[0]->child).push_back(newNode('M'));
(root->child[3]->child[2]->child).push_back(newNode('L'));
cout << calculateWays(root); ;
return 0;
}
Output :
576
Time Complexity: We visit each node once during the level order traversal and take
O(n) time to compute factorial for every node. Total time taken is O(Nn) where N =
1765
Chapter 295. Number of ways to traverse an N-ary tree
number of nodes in the n-ary tree. We can optimize the solution to work in O(N) time by
per-computing factorials of all numbers from 1 to n.
Auxiliary Space : Since we are only using a queue and a structure for every node, so
overall space complexity is also O(N).
Common Pitfalls: Since, products of factorials can tend to grow very huge, so it may
overflow. It is preferable to use data types like- unsigned long long int in C/C++, as the
number of ways can never be a negative number. In Java and Python there are Big Integer
to take care of overflows.
Source
https://www.geeksforgeeks.org/number-of-ways-to-traverse-an-n-ary-tree/
1766
Chapter 296
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) - GeeksforGeeks
We have discussed Overview of Array, Linked List, Queue and Stack. In this article following
Data Structures are discussed.
5. Binary Tree
6. Binary Search Tree
7. Binary Heap
9. Hashing
Binary Tree
Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are
hierarchical data structures.
A binary tree is a tree data structure in which each node has at most two children, which
are referred to as the left child and the right child. It is implemented mainly using Links.
Binary Tree Representation: A tree is represented by a pointer to the topmost node in
tree. If the tree is empty, then value of root is NULL. A Binary Tree node contains following
parts.
1. Data
2. Pointer to left child
3. Pointer to right child
A Binary Tree can be traversed in two ways:
Depth First Traversal: Inorder (Left-Root-Right), Preorder (Root-Left-Right) and Postorder
(Left-Right-Root)
Breadth First Traversal: Level Order Traversal
Binary Tree Properties:
1767
Chapter 296. Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Examples : One reason to use binary tree or tree in general is for the things that form
a hierarchy. They are useful in File structures where each file is located in a particular
directory and there is a specific hierarchy associated with files and directories. Another
example where Trees are useful is storing heirarchical objects like JavaScript Document
Object Model considers HTML page as a tree with nesting of tags as parent child relations.
Binary Search Tree
In Binary Search Tree is a Binary Tree with following additional properties:
1. The left subtree of a node contains only nodes with keys less than the node’s key.
2. The right subtree of a node contains only nodes with keys greater than the node’s key.
3. The left and right subtree each must also be a binary search tree.
Time Complexities:
Search : O(h)
Insertion : O(h)
Deletion : O(h)
Extra Space : O(n) for pointers
h: Height of BST
n: Number of nodes in BST
BST provide moderate access/search (quicker than Linked List and slower than arrays).
BST provide moderate insertion/deletion (quicker than Arrays and slower than Linked
Lists).
Examples : Its main use is in search application where data is constantly entering/leaving
and data needs to printed in sorted order. For example in implementation in E- commerce
1768
Chapter 296. Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
websites where a new product is added or product goes out of stock and all products are
lised in sorted order.
Binary Heap
A Binary Heap is a Binary Tree with following properties.
1) It’s a complete tree (All levels are completely filled except possibly the last level and the
last level has all keys as left as possible). This property of Binary Heap makes them suitable
to be stored in an array.
2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at
root must be minimum among all keys present in Binary Heap. The same property must
be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to Min Heap.
It is mainly implemented using array.
Get Minimum in Min Heap: O(1) [Or Get Max in Max Heap]
Extract Minimum Min Heap: O(Log n) [Or Extract Max in Max Heap]
Decrease Key in Min Heap: O(Log n) [Or Extract Max in Max Heap]
Insert: O(Log n)
Delete: O(Log n)
Example : Used in implementing efficient priority-queues, which in turn are used for
scheduling processes in operating systems. Priority Queues are also used in Dijstra’s and
Prim’s graph algorithms.
The Heap data structure can be used to efficiently find the k smallest (or largest) elements
in an array, merging k sorted arrays, median of a stream, etc.
Heap is a special data structure and it cannot be used for searching of a particular element.
HashingHash Function: A function that converts a given big input key to a small practi-
cal integer value. The mapped integer value is used as an index in hash table. A good hash
function should have following properties
1) Efficiently computable.
2) Should uniformly distribute the keys (Each table position equally likely for each key)
Hash Table: An array that stores pointers to records corresponding to a given phone number.
An entry in hash table is NIL if no existing phone number has hash function value equal to
the index for the entry.
Collision Handling: Since a hash function gets us a small number for a key which is a big
integer or string, there is possibility that two keys result in same value. The situation where
a newly inserted key maps to an already occupied slot in hash table is called collision and
must be handled using some collision handling technique. Following are the ways to handle
collisions:
Chaining:The idea is to make each cell of hash table point to a linked list of records that
have same hash function value. Chaining is simple, but requires additional memory outside
the table.
Open Addressing: In open addressing, all elements are stored in the hash table itself. Each
table entry contains either a record or NIL. When searching for an element, we one by one
examine table slots until the desired element is found or it is clear that the element is not
in the table.
1769
Chapter 296. Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Space : O(n)
Search : O(1) [Average] O(n) [Worst case]
Insertion : O(1) [Average] O(n) [Worst Case]
Deletion : O(1) [Average] O(n) [Worst Case]
Hashing seems better than BST for all the operations. But in hashing, elements are un-
ordered and in BST elements are stored in an ordered manner. Also BST is easy to imple-
ment but hash functions can sometimes be very complex to generate. In BST, we can also
efficiently find floor and ceil of values.
Example : Hashing can be used to remove duplicates from a set of elements. Can also
be used find frequency of all items. For example, in web browsers, we can check visited
urls using hashing. In firewalls, we can use hashing to detect spam. We need to hash IP
addresses. Hashing can be used in any situation where want search() insert() and delete()
in O(1) time.
This article is contributed by Abhiraj Smit. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : Rahul1421
Source
https://www.geeksforgeeks.org/overview-of-data-structures-set-2-binary-tree-bst-heap-and-hash/
1770
Chapter 297
Input : ((())(()
Range : 1 5
Range : 3 8
Output : 2
2
Explanation : In range 1 to 5 ((()),
there are the two pairs. In range 3 to 8 ())
((), there are the two pairs.
Input : )()()))
Range : 1 2
Range : 4 7
Output : 0
1
Explanation : In range 1 to 2 )( there
is no any pair. In range 4 to 7 ())),
there is the only pair
1771
Chapter 297. Pairs involved in Balanced Parentheses
vectors or etc.
For each node keep three integers :
1. t = Answer for the interval.
2. o = The number of opening brackets ‘(‘ remaining after deleting the brackets those who
belong to the correct bracket sequence in this interval whit length t.
3. c = The number of closing brackets ‘)’ remaining after deleting the brackets those who
belong to the correct bracket sequence in this interval whit length t.
Now, having these variables, queries can be answered easily using segment tree.
Below is the implementation of above approach :
1772
Chapter 297. Pairs involved in Balanced Parentheses
1773
Chapter 297. Pairs involved in Balanced Parentheses
int mid = (l + r) / 2;
// For left tree
struct node a =
segment(x, y, 2 * id, l, mid, s);
// For right tree
struct node b =
segment(x, y, 2 * id + 1, mid, r, s);
// Same as made in build function
int temp;
temp = min(a.o, b.c);
struct node vis;
vis.t = a.t + b.t + temp;
vis.o = a.o + b.o - temp;
vis.c = a.c + b.c - temp;
return vis;
}
// Driver code
int main()
{
string s = "((())(()";
int n = s.size();
// range for query
int a = 3, b = 8;
build(1, 0, n, s);
// Here we consider query's interval as [a, b)
// We subtract 1 from 'a' because indexes start
// from 0.
struct node p = segment(a-1, b, 1, 0, n, s);
cout << p.t << endl;
return 0;
}
Output:
1774
Chapter 297. Pairs involved in Balanced Parentheses
Source
https://www.geeksforgeeks.org/pairs-involved-balanced-parentheses/
1775
Chapter 298
1776
Chapter 298. Pairwise Swap leaf nodes in a binary tree
The sequence of leaf nodes in original binary tree from left to right is (4, 6, 7, 9, 10). Now
if we try to form pairs from this sequence, we will have two pairs as (4, 6), (7, 9). The last
node (10) is unable to form pair with any node and thus left unswapped.
The idea to solve this problem is to first traverse the leaf nodes of the binary tree from left
to right.
While traversing the leaf nodes, we maintain two pointers to keep track of first and second
leaf nodes in a pair and a variable count to keep track of count of leaf nodes traversed.
Now, if we observe carefully then we see that while traversing if the count of leaf nodes
traversed is even, it means that we can form a pair of leaf nodes. To keep track of this pair
we take two pointers firstPtr and secondPtr as mentioned above. Every time we encounter
a leaf node we initialize secondPtr with this leaf node. Now if the count is odd, we initialize
firstPtr with secondPtr otherwise we simply swap these two nodes.
Below is the C++ implementation of above idea:
1777
Chapter 298. Pairwise Swap leaf nodes in a binary tree
*b = temp;
}
// two pointers to keep track of
// first and second nodes in a pair
Node **firstPtr;
Node **secondPtr;
// function to pairwise swap leaf
// nodes from left to right
void pairwiseSwap(Node **root, int &count)
{
// if node is null, return
if (!(*root))
return;
// if node is leaf node, increment count
if(!(*root)->left&&!(*root)->right)
{
// initialize second pointer
// by current node
secondPtr = root;
// increment count
count++;
// if count is even, swap first
// and second pointers
if (count%2 == 0)
Swap(firstPtr, secondPtr);
else
// if count is odd, initialize
// first pointer by second pointer
firstPtr = secondPtr;
}
// if left child exists, check for leaf
// recursively
if ((*root)->left)
pairwiseSwap(&(*root)->left, count);
// if right child exists, check for leaf
// recursively
if ((*root)->right)
pairwiseSwap(&(*root)->right, count);
1778
Chapter 298. Pairwise Swap leaf nodes in a binary tree
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// function to print inorder traversal
// of binary tree
void printInorder(Node* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);
/* then print the data of node */
printf("%d ", node->data);
/* now recur on right child */
printInorder(node->right);
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in
// above diagram
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(8);
root->right->left->left = newNode(6);
root->right->left->right = newNode(7);
root->right->right->left = newNode(9);
root->right->right->right = newNode(10);
// print inorder traversal before swapping
cout << "Inorder traversal before swap:\n";
printInorder(root);
cout << "\n";
1779
Chapter 298. Pairwise Swap leaf nodes in a binary tree
// variable to keep track
// of leafs traversed
int c = 0;
// Pairwise swap of leaf nodes
pairwiseSwap(&root, c);
// print inorder traversal after swapping
cout << "Inorder traversal after swap:\n";
printInorder(root);
cout << "\n";
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/pairwise-swap-leaf-nodes-binary-tree/
1780
Chapter 299
1781
Chapter 299. Palindromic Tree | Introduction & Implementation
x will be a single character for every edge. Therefore, a node can have max 26 insertion
edges (considering lower letter string). We will use orange color for this edge in our pictorial
representation.
Maximum Palindromic Suffix Edge:
As the name itself indicates that for a node this edge will point to its Maximum Palindromic
Suffix String node. We will not be considering the complete string itself as the Maximum
Palindromic Suffix as this will make no sense(self loops). For simplicity purpose, we will
call it as Suffix edge(by which we mean maximum suffix except the complete string). It is
quite obvious that every node will have only 1 Suffix Edge as we will not store duplicate
strings in the tree. We will use Blue dashed edges for its Pictorial representation.
1782
Chapter 299. Palindromic Tree | Introduction & Implementation
will also have its suffix edge connected to Root-1 as for a null string (length 0) there is no
real palindromic suffix string of length less than 0.
1783
Chapter 299. Palindromic Tree | Introduction & Implementation
string X we just need to move down the suffix link for the current node i.e the node which
contains insertion of s[k]. See the below image for better understanding.
The current node in the below figure tells that it is the largest palindrome that ends at
index k after processing all the indices from 0 to k. The blue dotted path is the link of suffix
edges from current node to other processed nodes in the tree. String X will exist in one of
these nodes that lie on this chain of suffix link. All we need is to find it by iterating over it
down the chain.
To find the required node that contains the string X we will place the k+1 th character
at the end of every node that lies in suffix link chain and check if first character of the
corresponding suffix link string is equal to the k+1 th character.
Once, we find the X string we will direct an insertion edge with weight s[k+1] and link it
to the new node that contains largest palindrome ending at index k+1. The array elements
between the brackets as described in the figure below are the nodes that are stored in the
tree.
1784
Chapter 299. Palindromic Tree | Introduction & Implementation
There is one more thing left that is to be done. As we have created a new node at this
s[k+1] insertion , therefore we will also have to connect it with its suffix link child. Once,
again to do so we will use the above down the suffix link iteration from node X to find some
new string Y such that s[k+1] + Y + s[k+1] is a largest palindromic suffix for the newly
created node. Once, we find it we will then connect the suffix link of our newly created node
with the node Y.
Note : There are two possibilities when we find the string X. First possibility is that
string s[k+1]Xs[k+1] do not exist in the tree and second possibility is if it already exists
in the tree. In first case we will proceed the same way but in second case we will not
1785
Chapter 299. Palindromic Tree | Introduction & Implementation
create a new node separately but will just link the insertion edge from X to already existing
S[k+1]+X+S[k+1] node in the tree. We also need not to add the suffix link because the
node will already contain its suffix link.
Consider a string s = “abba” with length = 4.
At initial state we will have our two dummy root nodes one with length -1 ( some imaginary
string i ) and second a null string with length 0. At this point we haven’t inserted any
character in the tree. Root1 i.e root node with length -1 will be the current node from
which insertion takes place.
Stage 1: We will insert s[0] i.e ‘a‘.We will start checking from the current node i.e Root1.
Inserting ‘a’ at start and end of a string with length -1 will yield to a string with length 1
and this string will be “a”. Therefore, we create a new node “a” and direct insertion edge
from root1 to this new node. Now, largest palindromic suffix string for string of length 1
will be a null string so its suffix link will be directed to root2 i.e null string.Now the current
node will be this new node “a”.
1786
Chapter 299. Palindromic Tree | Introduction & Implementation
Stage 2: We will insert s[1] i.e ‘b‘. Insertion process will start from current node i.e “a”
node. We will traverse the suffix link chain starting from current node till we find suitable
X string , So here traversing the suffix link we again found root1 as X string. Once again
inserting ‘b’ to string of length -1 will yield a string of of length 1 i.e string “b”. Suffix link
for this node will go to null string as described in above insertion. Now the current node
will be this new node “b”.
1787
Chapter 299. Palindromic Tree | Introduction & Implementation
Stage 3: We will insert s[2] i.e ‘b‘. Once again starting from current node we will traverse
its suffix link to find required X string. In this case it founds to be root2 i.e null string as
adding ‘b’ at front and end of null string yields a palindrome “bb” of length 2. Therefore,
we will create a new node “bb” and will direct the insertion edge from the null string to the
newly created string. Now, the largest suffix palindrome for this current node will be node
“b”. So, we will link the suffix edge from this newly created node to node “b”. Current node
now becomes node “bb”.
1788
Chapter 299. Palindromic Tree | Introduction & Implementation
Stage 4: We will insert s[3] i.e ‘a‘. Insertion process begins with current node and in this
case the current node itself is the largest X string such that s[0] + X + s[3] is palindrome.
Therefore, we will create a new node “abba” and link the insertion edge from the current
node “bb” to this newly created node with edge weight ‘a’. Now, the suffix the link from
this newly created node will be linked to node “a” as that is the largest palindromic suffix.
1789
Chapter 299. Palindromic Tree | Introduction & Implementation
1790
Chapter 299. Palindromic Tree | Introduction & Implementation
{
// store start and end indexes of current
// Node inclusively
int start, end;
// stores length of substring
int length;
// stores insertion Node for all characters a-z
int insertEdg[26];
// stores the Maximum Palindromic Suffix Node for
// the current Node
int suffixEdg;
};
// two special dummy Nodes as explained above
Node root1, root2;
// stores Node information for constant time access
Node tree[MAXN];
// Keeps track the current Node while insertion
int currNode;
string s;
int ptr;
void insert(int idx)
{
//STEP 1//
/* search for Node X such that s[idx] X S[idx]
is maximum palindrome ending at position idx
iterate down the suffix link of currNode to
find X */
int tmp = currNode;
while (true)
{
int curLength = tree[tmp].length;
if (idx - curLength >= 1 and s[idx] == s[idx-curLength-1])
break;
tmp = tree[tmp].suffixEdg;
}
/* Now we have found X ....
* X = string at Node tmp
* Check : if s[idx] X s[idx] already exists or not*/
if(tree[tmp].insertEdg[s[idx]-'a'] != 0)
1791
Chapter 299. Palindromic Tree | Introduction & Implementation
{
// s[idx] X s[idx] already exists in the tree
currNode = tree[tmp].insertEdg[s[idx]-'a'];
return;
}
// creating new Node
ptr++;
// making new Node as child of X with
// weight as s[idx]
tree[tmp].insertEdg[s[idx]-'a'] = ptr;
// calculating length of new Node
tree[ptr].length = tree[tmp].length + 2;
// updating end point for new Node
tree[ptr].end = idx;
// updating the start for new Node
tree[ptr].start = idx - tree[ptr].length + 1;
//STEP 2//
/* Setting the suffix edge for the newly created
Node tree[ptr]. Finding some String Y such that
s[idx] + Y + s[idx] is longest possible
palindromic suffix for newly created Node.*/
tmp = tree[tmp].suffixEdg;
// making new Node as current Node
currNode = ptr;
if (tree[currNode].length == 1)
{
// if new palindrome's length is 1
// making its suffix link to be null string
tree[currNode].suffixEdg = 2;
return;
}
while (true)
{
int curLength = tree[tmp].length;
if (idx-curLength >= 1 and s[idx] == s[idx-curLength-1])
break;
tmp = tree[tmp].suffixEdg;
}
1792
Chapter 299. Palindromic Tree | Introduction & Implementation
// Now we have found string Y
// linking current Nodes suffix link with s[idx]+Y+s[idx]
tree[currNode].suffixEdg = tree[tmp].insertEdg[s[idx]-'a'];
}
// driver program
int main()
{
// initializing the tree
root1.length = -1;
root1.suffixEdg = 1;
root2.length = 0;
root2.suffixEdg = 1;
tree[1] = root1;
tree[2] = root2;
ptr = 2;
currNode = 1;
// given string
s = "abcbab";
int l = s.length();
for (int i=0; i<l; i++)
insert(i);
// printing all of its distinct palindromic
// substring
cout << "All distinct palindromic substring for "
<< s << " : \n";
for (int i=3; i<=ptr; i++)
{
cout << i-2 << ") ";
for (int j=tree[i].start; j<=tree[i].end; j++)
cout << s[j];
cout << endl;
}
return 0;
}
Output:
1793
Chapter 299. Palindromic Tree | Introduction & Implementation
3)c
4)bcb
5)abcba
6)bab
Time Complexity
The time complexity for the building process will be O(k*n), here “n” is the length of the
string and ‘k‘ is the extra iterations required to find the string X and string Y in the suffix
links every time we insert a character.Let’s try to approximate the constant ‘k’. We shall
consider a worst case like s = “aaaaaabcccccccdeeeeeeeeef”. In this case for similar
streak of continuous characters it will take extra 2 iterations per index to find both string
X and Y in the suffix links , but as soon as it reaches some index i such that s[i]!=s[i-1] the
left most pointer for the maximum length suffix will reach its rightmost limit. Therefore,
for all i when s[i]!=s[i-1] , it will cost in total n iterations(summing over each iteration) and
for rest i when s[i]==s[i-1] it takes 2 iteration which sums up over all such i and takes 2*n
iterations. Hence, approximately our complexity in this case will be O(3*n) ~ O(n).So, we
can roughly say that the constant factor ‘k’ will be very less. Therefore, we can consider
the overall complexity to be linear O(length of string). You may refer the reference links
for better understanding.
References :
• http://codeforces.com/blog/entry/13959
• http://adilet.org/blog/25-09-14/
Source
https://www.geeksforgeeks.org/palindromic-tree-introduction-implementation/
1794
Chapter 300
Input :
4
/ \
2 6
/ \ / \
1 3 5 7
/
9
/ \
12 10
\
11
/ \
45 13
\
14
1795
Chapter 300. Path length having maximum number of bends
Output : 6
In the above example, the path 4-> 6-> 7-> 9-> 10-> 11-> 45
is having the maximum number of bends, i.e., 3.
The length of this path is 6.
Approach :
The idea is to traverse the tree for left and right subtrees of the root. While traversing, keep
track of the direction of motion (left or right). Whenever, direction of motion changes from
left to right or vice versa increment the number of bends in the current path by 1.
On reaching the leaf node, compare the number of bends in the current path with the
maximum number of bends(i.e., maxBends) seen so far in a root-to-leaf path. If the number
of bends in the current path is greater than the maxBends, then update the maxBends equal
to the number of bends in the current path and update the maximum path length (i.e., len)
also to the length of the current path.
Implementation :
C++
1796
Chapter 300. Path length having maximum number of bends
1797
Chapter 300. Path length having maximum number of bends
}
else {
findMaxBendsUtil(node->left, 'l',
bends + 1, maxBends,
soFar + 1, len);
}
}
// Having both left and right child
else {
if (dir == 'l') {
findMaxBendsUtil(node->left, dir,
bends, maxBends,
soFar + 1, len);
findMaxBendsUtil(node->right, 'r',
bends + 1, maxBends,
soFar + 1, len);
}
else {
findMaxBendsUtil(node->right, dir,
bends, maxBends,
soFar + 1, len);
findMaxBendsUtil(node->left, 'l',
bends + 1, maxBends,
soFar + 1, len);
}
}
}
// Helper function to call findMaxBendsUtil()
int findMaxBends(struct Node* node)
{
if (node == NULL)
return 0;
int len = 0, bends = 0, maxBends = -1;
// Call for left subtree of the root
if (node->left)
findMaxBendsUtil(node->left, 'l',
bends, &maxBends, 1, &len);
// Call for right subtree of the root
if (node->right)
findMaxBendsUtil(node->right, 'r', bends,
&maxBends, 1, &len);
// Include the root node as well in the path length
len++;
1798
Chapter 300. Path length having maximum number of bends
return len;
}
// Driver code
int main()
{
/* Constructed binary tree is
10
/ \
8 2
/ \ /
3 5 2
\
1
/
9
*/
struct Node* root = newNode(10);
root->left = newNode(8);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->left = newNode(2);
root->right->left->right = newNode(1);
root->right->left->right->left = newNode(9);
cout << findMaxBends(root) - 1;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/path-length-maximum-number-bends/
1799
Chapter 301
1 2 3 4 7 5 6 8 15 9 14 10 13 11 12 16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24
i.e. print nodes in level order but nodes should be from left and right side alternatively.
Here 1st and 2nd levels are trivial.
While 3rd level: 4(left), 7(right), 5(left), 6(right) are printed.
While 4th level: 8(left), 15(right), 9(left), 14(right), .. are printed.
While 5th level: 16(left), 31(right), 17(left), 30(right), .. are printed.
We strongly recommend to minimize your browser and try this yourself first.
1800
Chapter 301. Perfect Binary Tree Specific Level Order Traversal
In standard Level Order Traversal, we enqueue root into a queue 1st , then we dequeue ONE
node from queue, process (print) it, enqueue its children into queue. We keep doing this
until queue is empty.
Approach 1:
We can do standard level order traversal here too but instead of printing nodes directly, we
have to store nodes in current level in a temporary array or list 1st and then take nodes
from alternate ends (left and right) and print nodes. Keep repeating this for all levels.
This approach takes more memory than standard traversal.
Approach 2:
The standard level order traversal idea will slightly change here. Instead of processing ONE
node at a time, we will process TWO nodes at a time. And while pushing children into
queue, the enqueue order will be: 1st node’s left child, 2nd node’s right child, 1st node’s
right child and 2nd node’s left child.
C++
1801
Chapter 301. Perfect Binary Tree Specific Level Order Traversal
1802
Chapter 301. Perfect Binary Tree Specific Level Order Traversal
{
//Perfect Binary Tree of Height 4
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->left->left->right = newNode(9);
root->left->right->left = newNode(10);
root->left->right->right = newNode(11);
root->right->left->left = newNode(12);
root->right->left->right = newNode(13);
root->right->right->left = newNode(14);
root->right->right->right = newNode(15);
root->left->left->left->left = newNode(16);
root->left->left->left->right = newNode(17);
root->left->left->right->left = newNode(18);
root->left->left->right->right = newNode(19);
root->left->right->left->left = newNode(20);
root->left->right->left->right = newNode(21);
root->left->right->right->left = newNode(22);
root->left->right->right->right = newNode(23);
root->right->left->left->left = newNode(24);
root->right->left->left->right = newNode(25);
root->right->left->right->left = newNode(26);
root->right->left->right->right = newNode(27);
root->right->right->left->left = newNode(28);
root->right->right->left->right = newNode(29);
root->right->right->right->left = newNode(30);
root->right->right->right->right = newNode(31);
cout << "Specific Level Order traversal of binary tree is \n";
printSpecificLevelOrder(root);
return 0;
}
Java
1803
Chapter 301. Perfect Binary Tree Specific Level Order Traversal
import java.util.LinkedList;
import java.util.Queue;
/* Class containing left and right child of current
node and key value*/
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
/* Given a perfect binary tree, print its nodes in specific
level order */
void printSpecificLevelOrder(Node node)
{
if (node == null)
return;
// Let us print root and next level first
System.out.print(node.data);
// Since it is perfect Binary Tree, right is not checked
if (node.left != null)
System.out.print(" " + node.left.data + " " + node.right.data);
// Do anything more if there are nodes at next level in
// given perfect Binary Tree
if (node.left.left == null)
return;
// Create a queue and enqueue left and right children of root
Queue<Node> q = new LinkedList<Node>();
q.add(node.left);
q.add(node.right);
// We process two nodes at a time, so we need two variables
// to store two front items of queue
Node first = null, second = null;
1804
Chapter 301. Perfect Binary Tree Specific Level Order Traversal
// traversal loop
while (!q.isEmpty())
{
// Pop two items from queue
first = q.peek();
q.remove();
second = q.peek();
q.remove();
// Print children of first and second in reverse order
System.out.print(" " + first.left.data + " " +second.right.data);
System.out.print(" " + first.right.data + " " +second.left.data);
// If first and second have grandchildren, enqueue them
// in reverse order
if (first.left.left != null)
{
q.add(first.left);
q.add(second.right);
q.add(first.right);
q.add(second.left);
}
}
}
// Driver program to test for above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.left.left.left = new Node(8);
tree.root.left.left.right = new Node(9);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(11);
tree.root.right.left.left = new Node(12);
tree.root.right.left.right = new Node(13);
tree.root.right.right.left = new Node(14);
tree.root.right.right.right = new Node(15);
1805
Chapter 301. Perfect Binary Tree Specific Level Order Traversal
Python
1806
Chapter 301. Perfect Binary Tree Specific Level Order Traversal
1807
Chapter 301. Perfect Binary Tree Specific Level Order Traversal
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.left.left.left = Node(8)
root.left.left.right = Node(9)
root.left.right.left = Node(10)
root.left.right.right = Node(11)
root.right.left.left = Node(12)
root.right.left.right = Node(13)
root.right.right.left = Node(14)
root.right.right.right = Node(15)
root.left.left.left.left = Node(16)
root.left.left.left.right = Node(17)
root.left.left.right.left = Node(18)
root.left.left.right.right = Node(19)
root.left.right.left.left = Node(20)
root.left.right.left.right = Node(21)
root.left.right.right.left = Node(22)
root.left.right.right.right = Node(23)
root.right.left.left.left = Node(24)
root.right.left.left.right = Node(25)
root.right.left.right.left = Node(26)
root.right.left.right.right = Node(27)
root.right.right.left.left = Node(28)
root.right.right.left.right = Node(29)
root.right.right.right.left = Node(30)
root.right.right.right.right = Node(31)
print "Specific Level Order traversal of binary tree is"
printSpecificLevelOrder(root);
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Followup Questions:
1. The above code prints specific level order from TOP to BOTTOM. How will you do
specific level order traversal from BOTTOM to TOP (Amazon Interview | Set 120 –
Round 1 Last Problem)
1808
Chapter 301. Perfect Binary Tree Specific Level Order Traversal
This article is contributed by Anurag Singh. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/perfect-binary-tree-specific-level-order-traversal/
1809
Chapter 302
16 31 17 30 18 29 19 28 20 27 21 26 22 25 23 24 8 15 9 14 10 13 11 12 4 7 5 6 2 3 1
The task is to print nodes in level order but nodes should be from left and right side
alternatively and from bottom – up manner
1810
Chapter 302. Perfect Binary Tree Specific Level Order Traversal | Set 2
We strongly recommend you to minimize your browser and try this yourself
first.
The standard level order traversal idea slightly changes here.
1. Instead of processing ONE node at a time, we will process TWO nodes at a time.
2. For dequeued nodes, we push node’s left and right child into stack in following manner
– 2nd node’s left child, 1st node’s right child, 2nd node’s right child and 1st node’s left
child.
3. And while pushing children into queue, the enqueue order will be: 1st node’s right
child, 2nd node’s left child, 1st node’s left child and 2nd node’s right child. Also, when
we process two queue nodes.
4. Finally pop all Nodes from stack and prints them.
C++
1811
Chapter 302. Perfect Binary Tree Specific Level Order Traversal | Set 2
q.push(root->right);
// We process two nodes at a time, so we
// need two variables to store two front
// items of queue
Node *first = NULL, *second = NULL;
// traversal loop
while (!q.empty())
{
// Pop two items from queue
first = q.front();
q.pop();
second = q.front();
q.pop();
// Push first and second node's chilren
// in reverse order
s.push(second->left);
s.push(first->right);
s.push(second->right);
s.push(first->left);
// If first and second have grandchildren,
// enqueue them in specific order
if (first->left->left != NULL)
{
q.push(first->right);
q.push(second->left);
q.push(first->left);
q.push(second->right);
}
}
}
/* Given a perfect binary tree, print its nodes in
specific level order */
void printSpecificLevelOrder(Node* root)
{
//create a stack and push root
stack<Node*> s;
//Push level 1 and level 2 nodes in stack
s.push(root);
// Since it is perfect Binary Tree, right is
// not checked
if (root->left != NULL)
1812
Chapter 302. Perfect Binary Tree Specific Level Order Traversal | Set 2
{
s.push(root->right);
s.push(root->left);
}
// Do anything more if there are nodes at next
// level in given perfect Binary Tree
if (root->left->left != NULL)
printSpecificLevelOrderUtil(root, s);
// Finally pop all Nodes from stack and prints
// them.
while (!s.empty())
{
cout << s.top()->data << " ";
s.pop();
}
}
/* Driver program to test above functions*/
int main()
{
// Perfect Binary Tree of Height 4
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
/* root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->left->left->right = newNode(9);
root->left->right->left = newNode(10);
root->left->right->right = newNode(11);
root->right->left->left = newNode(12);
root->right->left->right = newNode(13);
root->right->right->left = newNode(14);
root->right->right->right = newNode(15);
root->left->left->left->left = newNode(16);
root->left->left->left->right = newNode(17);
root->left->left->right->left = newNode(18);
root->left->left->right->right = newNode(19);
root->left->right->left->left = newNode(20);
root->left->right->left->right = newNode(21);
1813
Chapter 302. Perfect Binary Tree Specific Level Order Traversal | Set 2
root->left->right->right->left = newNode(22);
root->left->right->right->right = newNode(23);
root->right->left->left->left = newNode(24);
root->right->left->left->right = newNode(25);
root->right->left->right->left = newNode(26);
root->right->left->right->right = newNode(27);
root->right->right->left->left = newNode(28);
root->right->right->left->right = newNode(29);
root->right->right->right->left = newNode(30);
root->right->right->right->right = newNode(31);
*/
cout << "Specific Level Order traversal of binary "
"tree is \n";
printSpecificLevelOrder(root);
return 0;
}
Java
1814
Chapter 302. Perfect Binary Tree Specific Level Order Traversal | Set 2
1815
Chapter 302. Perfect Binary Tree Specific Level Order Traversal | Set 2
// Since it is perfect Binary Tree, right is
// not checked
if (root.left != null)
{
s.push(root.right);
s.push(root.left);
}
// Do anything more if there are nodes at next
// level in given perfect Binary Tree
if (root.left.left != null)
printSpecificLevelOrderUtil(root, s);
// Finally pop all Nodes from stack and prints
// them.
while (!s.empty())
{
System.out.print(s.peek().data + " ");
s.pop();
}
}
// Driver program to test the above functions
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
/* tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.left.left.left = new Node(8);
tree.root.left.left.right = new Node(9);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(11);
tree.root.right.left.left = new Node(12);
tree.root.right.left.right = new Node(13);
tree.root.right.right.left = new Node(14);
tree.root.right.right.right = new Node(15);
tree.root.left.left.left.left = new Node(16);
tree.root.left.left.left.right = new Node(17);
tree.root.left.left.right.left = new Node(18);
1816
Chapter 302. Perfect Binary Tree Specific Level Order Traversal | Set 2
Python3
1817
Chapter 302. Perfect Binary Tree Specific Level Order Traversal | Set 2
1818
Chapter 302. Perfect Binary Tree Specific Level Order Traversal | Set 2
root.left.right.left = Node(10)
root.left.right.right = Node(11)
root.right.left.left = Node(12)
root.right.left.right = Node(13)
root.right.right.left = Node(14)
root.right.right.right = Node(15)
root.left.left.left.left = Node(16)
root.left.left.left.right = Node(17)
root.left.left.right.left = Node(18)
root.left.left.right.right = Node(19)
root.left.right.left.left = Node(20)
root.left.right.left.right = Node(21)
root.left.right.right.left = Node(22)
root.left.right.right.right = Node(23)
root.right.left.left.left = Node(24)
root.right.left.left.right = Node(25)
root.right.left.right.left = Node(26)
root.right.left.right.right = Node(27)
root.right.right.left.left = Node(28)
root.right.right.left.right = Node(29)
root.right.right.right.left = Node(30)
root.right.right.right.right = Node(31)
'''
print("Specific Level Order traversal of "
"binary tree is")
root.printSpecificLevelOrder(root)
# This code is contributed by 'Vaibhav Kumar 12'
Output :
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/perfect-binary-tree-specific-level-order-traversal-set-2/
1819
Chapter 303
Segment Tree is itself a great data structure that comes into play in many cases. In this
post we will introduce the concept of Persistency in this data structure. Persistency, simply
means to retain the changes. But obviously, retaining the changes cause extra memory
consumption and hence affect the Time Complexity.
Our aim is to apply persistency in segment tree and also to ensure that it does not take
more than O(log n) time and space for each change.
Let’s think in terms of versions i.e. for each change in our segment tree we create a new
version of it.
We will consider our initial version to be Version-0. Now, as we do any update in the
segment tree we will create a new version for it and in similar fashion track the record for
all versions.
But creating the whole tree for every version will take O(n log n) extra space and O(n log
n) time. So, this idea runs out of time and memory for large number of versions.
Let’s exploit the fact that for each new update(say point update for simplicity) in segment
tree, At max logn nodes will be modified. So, our new version will only contain these log n
new nodes and rest nodes will be the same as previous version. Therefore, it is quite clear
that for each new version we only need to create these log n new nodes whereas the rest of
nodes can be shared from the previous version.
Consider the below figure for better visualization(click on the image for better view) :-
1820
Chapter 303. Persistent Segment Tree | Set 1 (Introduction)
Consider the segment tree with green nodes . Lets call this segment tree as version-0. The
left child for each node is connected with solid red edge where as the right child for each
node is connected with solid purple edge. Clearly, this segment tree consists of 15 nodes.
Now consider we need to make change in the leaf node 13 of version-0.
So, the affected nodes will be – node 13 , node 6 , node 3 , node 1.
1821
Chapter 303. Persistent Segment Tree | Set 1 (Introduction)
Therefore, for the new version (Version-1) we need to create only these 4 new nodes.
Now, lets construct version-1 for this change in segment tree. We need a new node 1 as it
is affected by change done in node 13. So , we will first create a new node 1�(yellow color)
. The left child for node 1� will be the same for left child for node 1 in version-0. So, we
connect the left child of node 1� with node 2 of version-0(red dashed line in figure). Let’s
now examine the right child for node 1� in version-1. We need to create a new node as it
is affected . So we create a new node called node 3� and make it the right child for node
1�(solid purple edge connection).
In the similar fashion we will now examine for node 3�. The left child is affected , So we
create a new node called node 6� and connect it with solid red edge with node 3� , where
as the right child for node 3� will be the same as right child of node 3 in version-0. So, we
will make the right child of node 3 in version-0 as the right child of node 3� in version-1(see
the purple dash edge.)
Same procedure is done for node 6� and we see that the left child of node 6� will be the left
child of node 6 in version-0(red dashed connection) and right child is newly created node
called node 13�(solid purple dashed edge).
Each yellow color node is a newly created node and dashed edges are the inter-connection
between the different versions of the segment tree.
Now, the Question arises : How to keep track of all the versions?
– We only need to keep track the first root node for all the versions and this will serve the
purpose to track all the newly created nodes in the different versions. For this purpose we
can maintain an array of pointers to the first node of segment trees for all versions.
Let’s consider a very basic problem to see how to implement persistence in segment tree
We will create all the versions of the segment tree and keep track of their root node.Then
for each range sum query we will pass the required version’s root node in our query function
and output the required sum.
Below is the C++ implementation for the above problem:-
1822
Chapter 303. Persistent Segment Tree | Set 1 (Introduction)
1823
Chapter 303. Persistent Segment Tree | Set 1 (Introduction)
1824
Chapter 303. Persistent Segment Tree | Set 1 (Introduction)
int p2 = query(n->right,mid+1,high,l,r);
return p1+p2;
}
int main(int argc, char const *argv[])
{
int A[] = {1,2,3,4,5};
int n = sizeof(A)/sizeof(int);
for (int i=0; i<n; i++)
arr[i] = A[i];
// creating Version-0
node* root = new node(NULL, NULL, 0);
build(root, 0, n-1);
// storing root node for version-0
version[0] = root;
// upgrading to version-1
version[1] = new node(NULL, NULL, 0);
upgrade(version[0], version[1], 0, n-1, 4, 1);
// upgrading to version-2
version[2] = new node(NULL, NULL, 0);
upgrade(version[1],version[2], 0, n-1, 2, 10);
cout << "In version 1 , query(0,4) : ";
cout << query(version[1], 0, n-1, 0, 4) << endl;
cout << "In version 2 , query(3,4) : ";
cout << query(version[2], 0, n-1, 3, 4) << endl;
cout << "In version 0 , query(0,3) : ";
cout << query(version[0], 0, n-1, 0, 3) << endl;
return 0;
}
Output:
In version 1 , query(0,4) : 11
In version 2 , query(3,4) : 5
In version 0 , query(0,3) : 10
Note : The above problem can also be solved by processing the queries offline by sorting it
with respect to the version and answering the queries just after the corresponding update.
1825
Chapter 303. Persistent Segment Tree | Set 1 (Introduction)
Time Complexity : The time complexity will be the same as the query and point update
operation in the segment tree as we can consider the extra node creation step to be done
in O(1). Hence, the overall Time Complexity per query for new version creation and range
sum query will be O(log n).
Source
https://www.geeksforgeeks.org/persistent-segment-tree-set-1-introduction/
1826
Chapter 304
struct node
{
int data;
struct node* left;
struct node* right;
struct node* next;
}
Initially, all next pointers have NULL values. Your function should fill these next pointers
so that they point to inorder successor.
Solution (Use Reverse Inorder Traversal)
Traverse the given tree in reverse inorder traversal and keep track of previously visited node.
When a node is being visited, assign previously visited node as next.
C
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
1827
Chapter 304. Populate Inorder Successor for all nodes
1828
Chapter 304. Populate Inorder Successor for all nodes
/ \
8 12
/
3
*/
struct node *root = newnode(10);
root->left = newnode(8);
root->right = newnode(12);
root->left->left = newnode(3);
// Populates nextRight pointer in all nodes
populateNext(root);
// Let us see the populated values
struct node *ptr = root->left->left;
while(ptr)
{
// -1 is printed if there is no successor
printf("Next of %d is %d \n", ptr->data, ptr->next? ptr->next->data: -1);
ptr = ptr->next;
}
return 0;
}
Java
1829
Chapter 304. Populate Inorder Successor for all nodes
reverse Inorder */
void populateNext(Node node)
{
// The first visited node will be the rightmost node
// next of the rightmost node will be NULL
if (node != null)
{
// First set the next pointer in right subtree
populateNext(node.right);
// Set the next as previously visited node in reverse Inorder
node.next = next;
// Change the prev for subsequent node
next = node;
// Finally, set the next pointer in left subtree
populateNext(node.left);
}
}
/* Driver program to test above functions*/
public static void main(String args[])
{
/* Constructed binary tree is
10
/ \
8 12
/
3 */
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(8);
tree.root.right = new Node(12);
tree.root.left.left = new Node(3);
// Populates nextRight pointer in all nodes
tree.populateNext(tree.root);
// Let us see the populated values
Node ptr = tree.root.left.left;
while (ptr != null)
{
// -1 is printed if there is no successor
int print = ptr.next != null ? ptr.next.data : -1;
System.out.println("Next of " + ptr.data + " is: " + print);
ptr = ptr.next;
}
1830
Chapter 304. Populate Inorder Successor for all nodes
}
}
// This code has been contributed by Mayank Jaiswal
We can avoid the use of static variable by passing reference to next as paramater.
C
Java
1831
Chapter 304. Populate Inorder Successor for all nodes
}
/* Set next of all descendents of p by traversing them in reverse Inorder */
void populateNextRecur(Node p, Node next_ref) {
if (p != null) {
// First set the next pointer in right subtree
populateNextRecur(p.right, next_ref);
// Set the next as previously visited node in reverse Inorder
p.next = next_ref;
// Change the prev for subsequent node
next_ref = p;
// Finally, set the next pointer in right subtree
populateNextRecur(p.left, next_ref);
}
}
Source
https://www.geeksforgeeks.org/populate-inorder-successor-for-all-nodes/
1832
Chapter 305
Possible edges of a tree for given diameter, height and vertices - GeeksforGeeks
Find a tree with the given values and print the edges of the tree. Print “-1”, if the tree is
not possible.
Given three integers n, d and h.
Examples :
Input : n = 5, d = 3, h = 2
Output : 1 2
2 3
1 4
1 5
Explanation :
Input : n = 8, d = 4, h = 2
Output : 1 2
1833
Chapter 305. Possible edges of a tree for given diameter, height and vertices
2 3
1 4
4 5
1 6
1 7
1 8
Explanation :
1. Observe that when d = 1, we cannot construct a tree (if tree has more than 2 vertices).
Also when d > 2*h, we cannot construct a tree.
2. As we know that height is the longest path from vertex 1 to another vertex. So build
that path from vertex 1 by adding edges up to h. Now, if d > h, we should add another
path to satisfy diameter from vertex 1, with a length of d – h.
3. Our conditions for height and diameter are satisfied. But still some vertices may be
left. Add the remaining vertices at any vertex other than the end points. This step
will not alter our diameter and height. Chose vertex 1 to add the remaining vertices
(you can chose any).
4. But when d == h, choose vertex 2 to add the remaining vertices.
CPP
1834
Chapter 305. Possible edges of a tree for given diameter, height and vertices
// edges up to h
for (int i = 1; i <= h; i++)
cout << i << " " << i + 1 << endl;
if (d > h) {
// Add d - h edges from 1 to
// satisfy diameter condition
cout << "1"
<< " " << h + 2 << endl;
for (int i = h + 2; i <= d; i++) {
cout << i << " " << i + 1 << endl;
}
}
// Remaining edges at vertex 1 or 2(d == h)
for (int i = d + 1; i < n; i++)
{
int k = 1;
if (d == h)
k = 2;
cout << k << " " << i + 1 << endl;
}
}
// Driver Code
int main()
{
int n = 5, d = 3, h = 2;
constructTree(n, d, h);
return 0;
}
Python3
1835
Chapter 305. Possible edges of a tree for given diameter, height and vertices
return 0
if d > 2 * h:
print("-1")
return 0
# Satisfy the height condition by add
# edges up to h
for i in range(1, h+1):
print(i," " , i + 1)
if d > h:
# Add d - h edges from 1 to
# satisfy diameter condition
print(1," ", h + 2)
for i in range(h+2, d+1):
print(i, " " , i + 1)
# Remaining edges at vertex 1 or 2(d == h)
for i in range(d+1, n):
k = 1
if d == h:
k = 2
print(k ," " , i + 1)
# Driver Code
n = 5
d = 3
h = 2
constructTree(n, d, h)
# This code is contributed by "Sharad_Bhardwaj".
Output :
1 2
2 3
1 4
1 5
Source
https://www.geeksforgeeks.org/print-possible-edges-tree-given-diameter-height-vertices/
1836
Chapter 306
Input : 24
Output : 10
A simple solution is to first store Postorder traversal of the given tree in an array then
linearly search given node and print node next to it.
Time Complexity : O(n)
Auxiliary Space : O(n)
An efficient solution is based on below observations.
1837
Chapter 306. Postorder predecessor of a Node in Binary Search Tree
1. If right child of given node exists, then the right child is postorder predecessor.
2. If right child does not exist and given node is left child of its parent, then its sibling
is its postorder predecessor.
3. If none of above conditions are satisfied (left child does not exist and given node is
not right child of its parent), then we move up using parent pointers until one of the
following happens.
• We reach root. In this case, postorder predecessor does not exiss
• Current node (one of the ancestors of given node) is right child of its parent, in
this case postorder predecessor is sibling of current node.
1838
Chapter 306. Postorder predecessor of a Node in Binary Search Tree
return NULL;
return parent->left;
}
int main()
{
Node* root = newNode(20);
root->parent = NULL;
root->left = newNode(10);
root->left->parent = root;
root->left->left = newNode(4);
root->left->left->parent = root->left;
root->left->right = newNode(18);
root->left->right->parent = root->left;
root->right = newNode(26);
root->right->parent = root;
root->right->left = newNode(24);
root->right->left->parent = root->right;
root->right->right = newNode(27);
root->right->right->parent = root->right;
root->left->right->left = newNode(14);
root->left->right->left->parent = root->left->right;
root->left->right->left->left = newNode(13);
root->left->right->left->left->parent = root->left->right->left;
root->left->right->left->right = newNode(15);
root->left->right->left->right->parent = root->left->right->left;
root->left->right->right = newNode(19);
root->left->right->right->parent = root->left->right;
Node* res = postorderPredecessor(root, root->left->right->right);
if (res) {
printf("Postorder predecessor of %d is %d\n",
root->left->right->right->key, res->key);
}
else {
printf("Postorder predecessor of %d is NULL\n",
root->left->right->right->key);
}
return 0;
}
Output:
Postorder predecessor of 19 is 14
1839
Chapter 306. Postorder predecessor of a Node in Binary Search Tree
Source
https://www.geeksforgeeks.org/postorder-predecessor-node-binary-search-tree/
1840
Chapter 307
Input : 24
Output : 27
Input : 4
Output : 13
A simple solution is to first store Postorder traversal of the given tree in an array then
linearly search given node and print node next to it.
Time Complexity : O(n)
Auxiliary Space : O(n)
1841
Chapter 307. Postorder successor of a Node in Binary Tree
1. If given node is root then postorder successor is NULL, since root is the last node
print in a postorder traversal
2. If given node is right child of parent or right child of parent is NULL, then parent is
postorder successor.
3. If given node is left child of parent and right child of parent is not NULL, then postorder
successor is the leftmost node of parent’s right subtree
1842
Chapter 307. Postorder successor of a Node in Binary Tree
return curr;
}
// Driver code
int main()
{
struct Node* root = newNode(20);
root->parent = NULL;
root->left = newNode(10);
root->left->parent = root;
root->left->left = newNode(4);
root->left->left->parent = root->left;
root->left->right = newNode(18);
root->left->right->parent = root->left;
root->right = newNode(26);
root->right->parent = root;
root->right->left = newNode(24);
root->right->left->parent = root->right;
root->right->right = newNode(27);
root->right->right->parent = root->right;
root->left->right->left = newNode(14);
root->left->right->left->parent = root->left->right;
root->left->right->left->left = newNode(13);
root->left->right->left->left->parent = root->left->right->left;
root->left->right->left->right = newNode(15);
root->left->right->left->right->parent = root->left->right->left;
root->left->right->right = newNode(19);
root->left->right->right->parent = root->left->right;
struct Node* res = postorderSuccessor(root, root->left->right->right);
if (res)
printf("Postorder successor of %d is %d\n",
root->left->right->right->value, res->value);
else
printf("Postorder successor of %d is NULL\n",
root->left->right->right->value);
return 0;
}
Output:
Postorder successor of 19 is 18
1843
Chapter 307. Postorder successor of a Node in Binary Tree
Source
https://www.geeksforgeeks.org/postorder-successor-node-binary-tree/
1844
Chapter 308
Postorder traversal of Binary Tree without recursion and without stack - GeeksforGeeks
Prerequisite – Inorder/preorder/postorder traversal of tree
Given a binary tree, perform postorder traversal.
We have discussed below methods for postorder traversal.
1) Recursive Postorder Traversal.
2) Postorder traversal using Stack.
2) Postorder traversal using two Stacks.
In this method a DFS based solution is discussed. We keep track of visited nodes in a hash
table.
1845
Chapter 308. Postorder traversal of Binary Tree without recursion and without stack
1846
Chapter 308. Postorder traversal of Binary Tree without recursion and without stack
Output:
1 4 7 6 3 13 14 10 8
Alternate Solution:
We can keep visited flag with every node instead of separate hash table.
1847
Chapter 308. Postorder traversal of Binary Tree without recursion and without stack
node->visited = false;
return (node);
}
/* Driver program to test above functions*/
int main()
{
struct Node* root = newNode(8);
root->left = newNode(3);
root->right = newNode(10);
root->left->left = newNode(1);
root->left->right = newNode(6);
root->left->right->left = newNode(4);
root->left->right->right = newNode(7);
root->right->right = newNode(14);
root->right->right->left = newNode(13);
postorder(root);
return 0;
}
Output:
1 4 7 6 3 13 14 10 8
Time complexity of above solution is O(n2 ) in worst case we move pointer back to head
after visiting every node.
Source
https://www.geeksforgeeks.org/postorder-traversal-binary-tree-without-recursion-without-stack/
1848
Chapter 309
• If there are n nodes in AVL tree, minimum height of AVL tree is floor(log2 n).
• If there are n nodes in AVL tree, maximum height can’t exceed 1.44*log2 n.
• If height of AVL tree is h, maximum number of nodes can be 2h+1 – 1.
• Minimum number of nodes in a tree with height h can be represented as:
N(h) = N(h-1) + N(h-2) + 1 for n>2 where N(0) = 1 and N(1) = 2.
• The complexity of searching, inserting and deletion in AVL tree is O(log n).
1849
Chapter 309. Practice questions on Height balanced/AVL Tree
1850
Chapter 309. Practice questions on Height balanced/AVL Tree
= Θ(log(n*2^n))
= Θ(log(n)) + Θ(log(2^n))
= Θ(log(n)) + Θ(nlog(2))
= Θ(log(n)) + Θ(n)
As logn is asymptotically smaller than n, Θ(log(n)) + Θ(n) can be written as Θ(n) which
matches option C.
Type 3: Insertion and Deletion in AVL tree –
The question can be asked on the resultant tree when keys are inserted or deleted from AVL
tree. Appropriate rotations need to be made if balance factor is disturbed.
Que – 5. Consider the following AVL tree.
1851
Chapter 309. Practice questions on Height balanced/AVL Tree
(B)
(C)
1852
Chapter 309. Practice questions on Height balanced/AVL Tree
(D) None
Solution: The element is first inserted in the same way as BST. Therefore after insertion
of 70, BST can be shown as:
1853
Chapter 309. Practice questions on Height balanced/AVL Tree
Source
https://www.geeksforgeeks.org/practice-questions-height-balancedavl-tree/
1854
Chapter 310
Input : 19
Output : 15
A simple solution is to first store Preorder traversal of the given tree in an array then
linearly search given node and print node next to it.
Time Complexity : O(n)
Auxiliary Space : O(n)
An efficient solution is based on below observations.
1855
Chapter 310. Preorder Successor of a Node in Binary Tree
1. If left child of given node exists, then the left child is preorder successor.
2. If left child does not exist and given node is left child of its parent, then its sibling is
its preorder successor.
3. If none of above conditions are satisfied (left child does not exist and given node is
not left child of its parent), then we move up using parent pointers until one of the
following happens.
• We reach root. In this case, preorder successor does not exist.
• Current node (one of the ancestors of given node) is left child of its parent, in
this case preorder successor is sibling of current node.
1856
Chapter 310. Preorder Successor of a Node in Binary Tree
return NULL;
return parent->right;
}
int main()
{
Node* root = newNode(20);
root->parent = NULL;
root->left = newNode(10);
root->left->parent = root;
root->left->left = newNode(4);
root->left->left->parent = root->left;
root->left->right = newNode(18);
root->left->right->parent = root->left;
root->right = newNode(26);
root->right->parent = root;
root->right->left = newNode(24);
root->right->left->parent = root->right;
root->right->right = newNode(27);
root->right->right->parent = root->right;
root->left->right->left = newNode(14);
root->left->right->left->parent = root->left->right;
root->left->right->left->left = newNode(13);
root->left->right->left->left->parent = root->left->right->left;
root->left->right->left->right = newNode(15);
root->left->right->left->right->parent = root->left->right->left;
root->left->right->right = newNode(19);
root->left->right->right->parent = root->left->right;
Node* res = preorderSuccessor(root, root->left->right->right);
if (res) {
printf("Preorder successor of %d is %d\n",
root->left->right->right->key, res->key);
}
else {
printf("Preorder successor of %d is NULL\n",
root->left->right->right->key);
}
return 0;
}
Output:
Preorder successor of 19 is 26
1857
Chapter 310. Preorder Successor of a Node in Binary Tree
Source
https://www.geeksforgeeks.org/preorder-successor-node-binary-tree/
1858
Chapter 311
The idea is to use stack like iterative preorder traversal of binary tree.
1) Create an empty stack to store nodes.
2) Push the root node to the stack.
3) Run a loop while the stack is not empty
….a) Pop the top node from stack.
1859
Chapter 311. Preorder Traversal of N-ary Tree Without Recursion
1860
Chapter 311. Preorder Traversal of N-ary Tree Without Recursion
it--;
nodes.push(*it);
}
}
}
// Driver program
int main()
{
/* Let us create below tree
* A
* / / \ \
* B F D E
* / \ | /|\
* K J G C H I
* / \ | |
* N M O L
*/
Node* root = newNode('A');
(root->child).push_back(newNode('B'));
(root->child).push_back(newNode('F'));
(root->child).push_back(newNode('D'));
(root->child).push_back(newNode('E'));
(root->child[0]->child).push_back(newNode('K'));
(root->child[0]->child).push_back(newNode('J'));
(root->child[2]->child).push_back(newNode('G'));
(root->child[3]->child).push_back(newNode('C'));
(root->child[3]->child).push_back(newNode('H'));
(root->child[3]->child).push_back(newNode('I'));
(root->child[0]->child[0]->child).push_back(newNode('N'));
(root->child[0]->child[0]->child).push_back(newNode('M'));
(root->child[3]->child[0]->child).push_back(newNode('O'));
(root->child[3]->child[2]->child).push_back(newNode('L'));
traverse_tree(root);
return 0;
}
Output:
A B K N M J F D G E C O H I L
Source
https://www.geeksforgeeks.org/preorder-traversal-of-n-ary-tree-without-recursion/
1861
Chapter 312
A naive method is to first construct the tree from given postorder and inorder, then use
simple recursive method to print preorder traversal of the constructed tree.
1862
Chapter 312. Preorder from Inorder and Postorder traversals
We can print preorder traversal without constructing the tree. The idea is, root is
always the first item in preorder traversal and it must be the last item in postorder traversal.
We first push right subtree to a stack, then left subtree and finally we push root. Finally
we print contents of stack. To find boundaries of left and right subtrees in post[] and in[],
we search root in in[], all elements before root in in[] are elements of left subtree and all
elements after root are elements of right subtree. In post[], all elements after index of root
in in[] are elements of right subtree. And elements before index (including the element at
index and excluding the first element) are elements of left subtree.
1863
Chapter 312. Preorder from Inorder and Postorder traversals
1864
Chapter 312. Preorder from Inorder and Postorder traversals
Output:
25 15 10 4 12 22 18 24 50 35 31 44 70 66 90
Time Complexity: The above function visits every node in array. For every visit, it calls
search which takes O(n) time. Therefore, overall time complexity of the function is O(n2 )
O(n) Solution
We can further optimize above solution to first hash all items of inorder traversal so that
we do not have to linearly search items. With hash table available to us, we can search an
item in O(1) time.
1865
Chapter 312. Preorder from Inorder and Postorder traversals
Output:
25 15 10 4 12 22 18 24 50 35 31 44 70 66 90
1866
Chapter 312. Preorder from Inorder and Postorder traversals
Source
https://www.geeksforgeeks.org/preorder-from-inorder-and-postorder-traversals/
1867
Chapter 313
Input : 19
Output : 15
A simple solution is to first store Preorder traversal of the given tree in an array then
linearly search given node and print node next to it.
Time Complexity : O(n)
Auxiliary Space : O(n)
An efficient solution is based on below observations.
1868
Chapter 313. Preorder predecessor of a Node in Binary Tree
1869
Chapter 313. Preorder predecessor of a Node in Binary Tree
// Driver code
int main()
{
struct Node* root = newNode(20);
root->parent = NULL;
root->left = newNode(10);
root->left->parent = root;
root->left->left = newNode(4);
root->left->left->parent = root->left;
root->left->right = newNode(18);
root->left->right->parent = root->left;
root->right = newNode(26);
root->right->parent = root;
root->right->left = newNode(24);
root->right->left->parent = root->right;
root->right->right = newNode(27);
root->right->right->parent = root->right;
root->left->right->left = newNode(14);
root->left->right->left->parent = root->left->right;
root->left->right->left->left = newNode(13);
root->left->right->left->left->parent = root->left->right->left;
root->left->right->left->right = newNode(15);
root->left->right->left->right->parent = root->left->right->left;
root->left->right->right = newNode(19);
root->left->right->right->parent = root->left->right;
struct Node* res = preorderPredecessor(root, root->left->right->right);
if (res)
printf("Preorder predecessor of %d is %d\n",
root->left->right->right->value, res->value);
else
printf("Preorder predecessor of %d is NULL\n",
root->left->right->right->value);
return 0;
}
Output:
Preorder predecessor of 19 is 15
1870
Chapter 313. Preorder predecessor of a Node in Binary Tree
Source
https://www.geeksforgeeks.org/preorder-predecessor-node-binary-tree/
1871
Chapter 314
1
/ \
2 3
/ \
4 5
/
7
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
/* A binary tree node has data, pointer to left child
and a pointer to right child */
1872
Chapter 314. Print Ancestors of a given node in Binary Tree
struct node
{
int data;
struct node* left;
struct node* right;
};
/* If target is present in tree, then prints the ancestors
and returns true, otherwise returns false. */
bool printAncestors(struct node *root, int target)
{
/* base cases */
if (root == NULL)
return false;
if (root->data == target)
return true;
/* If target is present in either left or right subtree of this node,
then print this node */
if ( printAncestors(root->left, target) ||
printAncestors(root->right, target) )
{
cout << root->data << " ";
return true;
}
/* Else return false */
return false;
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newnode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
1873
Chapter 314. Print Ancestors of a given node in Binary Tree
Java
1874
Chapter 314. Print Ancestors of a given node in Binary Tree
1875
Chapter 314. Print Ancestors of a given node in Binary Tree
Python
Output:
1876
Chapter 314. Print Ancestors of a given node in Binary Tree
421
Time Complexity: O(n) where n is the number of nodes in the given Binary Tree.
Source
https://www.geeksforgeeks.org/print-ancestors-of-a-given-node-in-binary-tree/
1877
Chapter 315
Algorithm:
1) If value of root’s key is greater than k1, then recursively call in left subtree.
2) If value of root’s key is in range, then print the root’s key.
3) If value of root’s key is smaller than k2, then recursively call in right subtree.
Implementation:
#include<stdio.h>
1878
Chapter 315. Print BST keys in the given range
1879
Chapter 315. Print BST keys in the given range
/* Constructing tree given in the above figure */
root = newNode(20);
root->left = newNode(8);
root->right = newNode(22);
root->left->left = newNode(4);
root->left->right = newNode(12);
Print(root, k1, k2);
getchar();
return 0;
}
Java
1880
Chapter 315. Print BST keys in the given range
}
/* if root's data lies in range, then prints root's data */
if (k1 <= node.data && k2 >= node.data) {
System.out.print(node.data + " ");
}
/* If root->data is smaller than k2, then only we can get o/p keys
in right subtree */
if (k2 > node.data) {
Print(node.right, k1, k2);
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
int k1 = 10, k2 = 25;
tree.root = new Node(20);
tree.root.left = new Node(8);
tree.root.right = new Node(22);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(12);
tree.Print(root, k1, k2);
}
}
// This code has been contributed by Mayank Jaiswal
Python
1881
Chapter 315. Print BST keys in the given range
Output:
12 20 22
Source
https://www.geeksforgeeks.org/print-bst-keys-in-the-given-range/
1882
Chapter 316
Output :
7
We strongly recommend you to minimize your browser and try this yourself
first.
1883
Chapter 316. Print Binary Tree in 2-Dimensions
1884
Chapter 316. Print Binary Tree in 2-Dimensions
// Process left child
print2DUtil(root->left, space);
}
// Wrapper over print2DUtil()
void print2D(Node *root)
{
// Pass initial space count as 0
print2DUtil(root, 0);
}
// Driver program to test above functions
int main()
{
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->left->left->right = newNode(9);
root->left->right->left = newNode(10);
root->left->right->right = newNode(11);
root->right->left->left = newNode(12);
root->right->left->right = newNode(13);
root->right->right->left = newNode(14);
root->right->right->right = newNode(15);
print2D(root);
return 0;
}
Output :
15
14
1885
Chapter 316. Print Binary Tree in 2-Dimensions
13
12
11
10
Source
https://www.geeksforgeeks.org/print-binary-tree-2-dimensions/
1886
Chapter 317
Input : 7
/ \
6 5
/ \ / \
4 3 2 1
Output :
7
5 6
1 2 3 4
Input : 7
/ \
16 1
/ \
4 13
Output :
7
1 16
4 13
Here we can use two Priority queue for print in sorted order. We create an empty queue
q and two priority queues, current_level and next_level. We use NULL as a separator
between two levels. Whenever we encounter NULL in normal level order traversal, we swap
current_level and next_level.
1887
Chapter 317. Print Binary Tree levels in sorted order
1888
Chapter 317. Print Binary Tree levels in sorted order
1889
Chapter 317. Print Binary Tree levels in sorted order
Output:
Source
https://www.geeksforgeeks.org/print-binary-tree-levels-sorted-order/
1890
Chapter 318
Print Binary Tree levels in sorted order | Set 2 (Using set) - GeeksforGeeks
Given a tree, print the level order traversal in sorted order.
Examples :
Input : 7
/ \
6 5
/ \ / \
4 3 2 1
Output :
7
5 6
1 2 3 4
Input : 7
/ \
16 1
/ \
4 13
Output :
7
1 16
4 13
1891
Chapter 318. Print Binary Tree levels in sorted order | Set 2 (Using set)
In this post, a set (which is implemented using balanced binary search tree) based solution
is discussed.
Approach :
1. Start level order traversal of tree.
2. Store all the nodes in a set(or any other similar data structures).
3. Print elements of set.
C++
1892
Chapter 318. Print Binary Tree levels in sorted order | Set 2 (Using set)
else {
s.insert(tmp->data);
if (tmp->left != nullptr)
q.push(tmp->left);
if (tmp->right != nullptr)
q.push(tmp->right);
}
}
}
// Driver code
int main()
{
Node* root = new Node(7);
root->left = new Node(6);
root->right = new Node(5);
root->left->left = new Node(4);
root->left->right = new Node(3);
root->right->left = new Node(2);
root->right->right = new Node(1);
sorted_level_order(root);
return 0;
}
Output:
7 5 6 1 2 3 4
Source
https://www.geeksforgeeks.org/print-binary-tree-levels-sorted-order-2/
1893
Chapter 319
Method 1 (Simple Solution) A simple way is to one by once search every node of first
tree in second tree. Time complexity of this solution is O(m * h) where m is number of
nodes in first tree and h is height of second tree.
Method 2 (Linear Time) We can find common elements in O(n) time.
1) Do inorder traversal of first tree and store the traversal in an auxiliary array ar1[]. See
1894
Chapter 319. Print Common Nodes in Two Binary Search Trees
sortedInorder() here.
2) Do inorder traversal of second tree and store the traversal in an auxiliary array ar2[]
3) Find intersection of ar1[] and ar2[]. See thisfor details.
Time complexity of this method is O(m+n) where m and n are number of nodes in first and
second tree respectively. This solution requires O(m+n) extra space.
Method 3 (Linear Time and limited Extra Space) We can find common elements in
O(n) time and O(h1 + h2) extra space where h1 and h2 are heights of first and second BSTs
respectively.
The idea is to use iterative inorder traversal. We use two auxiliary stacks for two BSTs.
Since we need to find common elements, whenever we get same element, we print it.
1895
Chapter 319. Print Common Nodes in Two Binary Search Trees
// push the Nodes of second tree in stack s2
else if (root2)
{
s2.push(root2);
root2 = root2->left;
}
// Both root1 and root2 are NULL here
else if (!s1.empty() && !s2.empty())
{
root1 = s1.top();
root2 = s2.top();
// If current keys in two trees are same
if (root1->key == root2->key)
{
cout << root1->key << " ";
s1.pop();
s2.pop();
// move to the inorder successor
root1 = root1->right;
root2 = root2->right;
}
else if (root1->key < root2->key)
{
// If Node of first tree is smaller, than that of
// second tree, then its obvious that the inorder
// successors of current Node can have same value
// as that of the second tree Node. Thus, we pop
// from s2
s1.pop();
root1 = root1->right;
// root2 is set to NULL, because we need
// new Nodes of tree 1
root2 = NULL;
}
else if (root1->key > root2->key)
{
s2.pop();
root2 = root2->right;
root1 = NULL;
}
}
1896
Chapter 319. Print Common Nodes in Two Binary Search Trees
1897
Chapter 319. Print Common Nodes in Two Binary Search Trees
Output:
4 7 9 10
This article is contributed by Ekta Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/print-common-nodes-in-two-binary-search-trees/
1898
Chapter 320
Examples:
1899
Chapter 320. Print Left View of a Binary Tree
Input :
1
/ \
2 3
/ \ \
4 5 6
Output : 1 2 4
Input :
1
/ \
2 3
\
4
\
5
\
6
Output :1 2 4 5 6
The left view contains all nodes that are first nodes in their levels. A simple solution is to
do level order traversal and print the first node in every level.
The problem can also be solved using simple recursive traversal. We can keep track of
level of a node by passing a parameter to all recursive calls. The idea is to keep track of
maximum level also. Whenever we see a node whose level is more than maximum level so
far, we print the node because this is the first node in its level (Note that we traverse the
left subtree before right subtree). Following is the implementation-
1900
Chapter 320. Print Left View of a Binary Tree
}
// Recursive function to print left view of a binary tree.
void leftViewUtil(struct node *root, int level, int *max_level)
{
// Base Case
if (root==NULL) return;
// If this is the first node of its level
if (*max_level < level)
{
printf("%d\t", root->data);
*max_level = level;
}
// Recur for left and right subtrees
leftViewUtil(root->left, level+1, max_level);
leftViewUtil(root->right, level+1, max_level);
}
// A wrapper over leftViewUtil()
void leftView(struct node *root)
{
int max_level = 0;
leftViewUtil(root, 1, &max_level);
}
// Driver Program to test above functions
int main()
{
struct node *root = newNode(12);
root->left = newNode(10);
root->right = newNode(30);
root->right->left = newNode(25);
root->right->right = newNode(40);
leftView(root);
return 0;
}
Java
1901
Chapter 320. Print Left View of a Binary Tree
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
/* Class to print the left view */
class BinaryTree
{
Node root;
static int max_level = 0;
// recursive function to print left view
void leftViewUtil(Node node, int level)
{
// Base Case
if (node==null) return;
// If this is the first node of its level
if (max_level < level)
{
System.out.print(" " + node.data);
max_level = level;
}
// Recur for left and right subtrees
leftViewUtil(node.left, level+1);
leftViewUtil(node.right, level+1);
}
// A wrapper over leftViewUtil()
void leftView()
{
leftViewUtil(root, 1);
}
/* testing for example nodes */
public static void main(String args[])
{
/* creating a binary tree and entering the nodes */
BinaryTree tree = new BinaryTree();
tree.root = new Node(12);
tree.root.left = new Node(10);
1902
Chapter 320. Print Left View of a Binary Tree
Python
1903
Chapter 320. Print Left View of a Binary Tree
root.right = Node(20)
root.right.left = Node(25)
root.right.right = Node(40)
leftView(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
12 10 25
Time Complexity: The function does a simple traversal of the tree, so the complexity is
O(n).
This article is contributed by Ramsai Chinthamani. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/print-left-view-binary-tree/
1904
Chapter 321
Input:
3
/ \
2 5
/ \
1 4
output:
Level of 1 is 3
Level of 2 is 2
1905
Chapter 321. Print Levels of all nodes in a Binary Tree
Level of 3 is 1
Level of 4 is 3
Level of 5 is 2
C++
1906
Chapter 321. Print Levels of all nodes in a Binary Tree
}
}
/* Utility function to create a new Binary Tree node */
struct Node* newNode(int data)
{
struct Node* temp = new struct Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
/* Driver function to test above functions */
int main()
{
struct Node* root = NULL;
/* Constructing tree given in the above figure */
root = newNode(3);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(1);
root->left->right = newNode(4);
printLevel(root);
return 0;
}
Java
1907
Chapter 321. Print Levels of all nodes in a Binary Tree
1908
Chapter 321. Print Levels of all nodes in a Binary Tree
above figure */
root = new Node(3);
root.left = new Node(2);
root.right = new Node(5);
root.left.left = new Node(1);
root.left.right = new Node(4);
printLevel(root);
}
}
// This code is contributed by Sumit Ghosh
Output :
Level of 3 is 1
Level of 2 is 2
Level of 5 is 2
Level of 1 is 3
Level of 4 is 3
Time Complexity: O(n) where n is the number of nodes in the given Binary Tree.
Source
https://www.geeksforgeeks.org/print-levels-nodes-binary-tree/
1909
Chapter 322
1
/ \
2 3
/ \ / \
4 5 6 7
Top view of the above binary tree is
4 2 1 3 7
1
/ \
2 3
\
4
\
5
\
6
Top view of the above binary tree is
2 1 3 6
1910
Chapter 322. Print Nodes in Top View of Binary Tree
The idea is to do something similar to vertical Order Traversal. Like vertical Order Traversal,
we need to nodes of same horizontal distance together. We do a level order traversal so that
the topmost node at a horizontal node is visited before any other node of same horizontal
distance below it. Hashing is used to check if a node at given horizontal distance is seen or
not.
C++
1911
Chapter 322. Print Nodes in Top View of Binary Tree
if (n->right != NULL)
q.push(make_pair(n->right, val + 1));
}
}
// function to create a new node
struct Node* newNode(int key)
{
struct Node* node = new Node;
node->data = key;
node->left = node->right = NULL;
return node;
}
// main function
int main()
{
/* Create following Binary Tree
1
/ \
2 3
\
4
\
5
\
6*/
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->left->right->right = newNode(5);
root->left->right->right->right = newNode(6);
topView(root);
return 0;
}
/* This code is contributed by Niteesh Kumar */
Java
1912
Chapter 322. Print Nodes in Top View of Binary Tree
class TreeNode {
// Members
int key;
TreeNode left, right;
// Constructor
public TreeNode(int key)
{
this.key = key;
left = right = null;
}
}
// A class to represent a queue item. The queue is used to do Level
// order traversal. Every Queue item contains node and horizontal
// distance of node from root
class QItem {
TreeNode node;
int hd;
public QItem(TreeNode n, int h)
{
node = n;
hd = h;
}
}
// Class for a Binary Tree
class Tree {
TreeNode root;
// Constructors
public Tree() { root = null; }
public Tree(TreeNode n) { root = n; }
// This method prints nodes in top view of binary tree
public void printTopView()
{
// base case
if (root == null) {
return;
}
// Creates an empty hashset
HashSet<Integer> set = new HashSet<>();
// Create a queue and add root to it
Queue<QItem> Q = new LinkedList<QItem>();
Q.add(new QItem(root, 0)); // Horizontal distance of root is 0
1913
Chapter 322. Print Nodes in Top View of Binary Tree
// Standard BFS or level order traversal loop
while (!Q.isEmpty()) {
// Remove the front item and get its details
QItem qi = Q.remove();
int hd = qi.hd;
TreeNode n = qi.node;
// If this is the first node at its horizontal distance,
// then this node is in top view
if (!set.contains(hd)) {
set.add(hd);
System.out.print(n.key + " ");
}
// Enqueue left and right children of current node
if (n.left != null)
Q.add(new QItem(n.left, hd - 1));
if (n.right != null)
Q.add(new QItem(n.right, hd + 1));
}
}
}
// Driver class to test above methods
public class Main {
public static void main(String[] args)
{
/* Create following Binary Tree
1
/ \
2 3
\
4
\
5
\
6*/
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(4);
root.left.right.right = new TreeNode(5);
root.left.right.right.right = new TreeNode(6);
Tree t = new Tree(root);
System.out.println("Following are nodes in top view of Binary Tree");
t.printTopView();
}
1914
Chapter 322. Print Nodes in Top View of Binary Tree
Output:
Time Complexity of the above implementation is O(n) where n is number of nodes in given
binary tree. The assumption here is that add() and contains() methods of HashSet work in
O(1) time.
This article is contributed by Rohan. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Improved By : Aarsee
Source
https://www.geeksforgeeks.org/print-nodes-top-view-binary-tree/
1915
Chapter 323
Print Postorder traversal from given Inorder and Preorder traversals - GeeksforGeeks
Given Inorder and Preorder traversals of a binary tree, print Postorder traversal.
Example:
Input:
Inorder traversal in[] = {4, 2, 5, 1, 3, 6}
Preorder traversal pre[] = {1, 2, 4, 5, 3, 6}
Output:
Postorder traversal is {4, 5, 2, 6, 3, 1}
1
/ \
2 3
/ \ \
4 5 6
A naive method is to first construct the tree, then use simple recursive method to print
postorder traversal of the constructed tree.
We can print postorder traversal without constructing the tree. The idea is,
root is always the first item in preorder traversal and it must be the last item in postorder
1916
Chapter 323. Print Postorder traversal from given Inorder and Preorder traversals
traversal. We first recursively print left subtree, then recursively print right subtree. Finally,
print root. To find boundaries of left and right subtrees in pre[] and in[], we search root in
in[], all elements before root in in[] are elements of left subtree and all elements after root
are elements of right subtree. In pre[], all elements after index of root in in[] are elements
of right subtree. And elements before index (including the element at index and excluding
the first element) are elements of left subtree.
C++
// C++ program to print postorder traversal from preorder and inorder traversals
#include <iostream>
using namespace std;
// A utility function to search x in arr[] of size n
int search(int arr[], int x, int n)
{
for (int i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
// Prints postorder traversal from given inorder and preorder traversals
void printPostOrder(int in[], int pre[], int n)
{
// The first element in pre[] is always root, search it
// in in[] to find left and right subtrees
int root = search(in, pre[0], n);
// If left subtree is not empty, print left subtree
if (root != 0)
printPostOrder(in, pre + 1, root);
// If right subtree is not empty, print right subtree
if (root != n - 1)
printPostOrder(in + root + 1, pre + root + 1, n - root - 1);
// Print root
cout << pre[0] << " ";
}
// Driver program to test above functions
int main()
{
int in[] = { 4, 2, 5, 1, 3, 6 };
int pre[] = { 1, 2, 4, 5, 3, 6 };
int n = sizeof(in) / sizeof(in[0]);
cout << "Postorder traversal " << endl;
printPostOrder(in, pre, n);
1917
Chapter 323. Print Postorder traversal from given Inorder and Preorder traversals
return 0;
}
Python3
Output:
Postorder traversal
4 5 2 6 3 1
1918
Chapter 323. Print Postorder traversal from given Inorder and Preorder traversals
Output:
4 5 2 6 3 1
Time Complexity: The above function visits every node in array. For every visit, it calls
search which takes O(n) time. Therefore, overall time complexity of the function is O(n2 )
The above solution can be optimized using hashing. We use a HashMap to store elements
and their indexes so that we can quickly find index of an element.
1919
Chapter 323. Print Postorder traversal from given Inorder and Preorder traversals
Output:
1920
Chapter 323. Print Postorder traversal from given Inorder and Preorder traversals
4 5 2 6 3 1
Source
https://www.geeksforgeeks.org/print-postorder-from-given-inorder-and-preorder-traversals/
1921
Chapter 324
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
The Right view contains all nodes that are last nodes in their levels. A simple solution is
to do level order traversal and print the last node in every level.
The problem can also be solved using simple recursive traversal. We can keep track of level
of a node by passing a parameter to all recursive calls. The idea is to keep track of maximum
level also. And traverse the tree in a manner that right subtree is visited before left subtree.
Whenever we see a node whose level is more than maximum level so far, we print the node
because this is the last node in its level (Note that we traverse the right subtree before left
subtree). Following is C implementation of this approach.
C
1922
Chapter 324. Print Right View of a Binary Tree
#include<stdlib.h>
struct Node
{
int data;
struct Node *left, *right;
};
// A utility function to create a new Binary Tree Node
struct Node *newNode(int item)
{
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
// Recursive function to print right view of a binary tree.
void rightViewUtil(struct Node *root, int level, int *max_level)
{
// Base Case
if (root==NULL) return;
// If this is the last Node of its level
if (*max_level < level)
{
printf("%d\t", root->data);
*max_level = level;
}
// Recur for right subtree first, then left subtree
rightViewUtil(root->right, level+1, max_level);
rightViewUtil(root->left, level+1, max_level);
}
// A wrapper over rightViewUtil()
void rightView(struct Node *root)
{
int max_level = 0;
rightViewUtil(root, 1, &max_level);
}
// Driver Program to test above functions
int main()
{
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
1923
Chapter 324. Print Right View of a Binary Tree
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
rightView(root);
return 0;
}
Java
1924
Chapter 324. Print Right View of a Binary Tree
max_level.max_level = level;
}
// Recur for right subtree first, then left subtree
rightViewUtil(node.right, level + 1, max_level);
rightViewUtil(node.left, level + 1, max_level);
}
void rightView()
{
rightView(root);
}
// A wrapper over rightViewUtil()
void rightView(Node node) {
rightViewUtil(node, 1, max);
}
// Driver program to test the above functions
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.right.left.right = new Node(8);
tree.rightView();
}
}
// This code has been contributed by Mayank Jaiswal
Python
1925
Chapter 324. Print Right View of a Binary Tree
self.right = None
# Recursive function to print right view of Binary Tree
# used max_level as reference list ..only max_level[0]
# is helpful to us
def rightViewUtil(root, level, max_level):
# Base Case
if root is None:
return
# If this is the last node of its level
if (max_level[0] < level):
print "%d " %(root.data),
max_level[0] = level
# Recur for right subtree first, then left subtree
rightViewUtil(root.right, level+1, max_level)
rightViewUtil(root.left, level+1, max_level)
def rightView(root):
max_level = [0]
rightViewUtil(root, 1, max_level)
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right = Node(8)
rightView(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
1 3 7 8
1926
Chapter 324. Print Right View of a Binary Tree
Source
https://www.geeksforgeeks.org/print-right-view-binary-tree-2/
1927
Chapter 325
1
/ \
2 3
/ \ / \
4 5 6 7
\ \
8 9
1928
Chapter 325. Print a Binary Tree in Vertical Order | Set 1
The idea is to traverse the tree once and get the minimum and maximum horizontal distance
with respect to root. For the tree shown above, minimum distance is -2 (for node with value
4) and maximum distance is 3 (For node with value 9).
Once we have maximum and minimum distances from root, we iterate for each vertical line
at distance minimum to maximum from root, and for each vertical line traverse the tree and
print the nodes which lie on that vertical line.
Algorithm:
1929
Chapter 325. Print a Binary Tree in Vertical Order | Set 1
min = hd;
else if hd is greater than max then
*max = hd;
Implementation:
Following is the implementation of above algorithm.
C++
#include <iostream>
using namespace std;
// A node of binary tree
struct Node
{
int data;
struct Node *left, *right;
};
// A utility function to create a new Binary Tree node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to find min and max distances with respect
// to root.
void findMinMax(Node *node, int *min, int *max, int hd)
{
// Base case
if (node == NULL) return;
// Update min and max
1930
Chapter 325. Print a Binary Tree in Vertical Order | Set 1
1931
Chapter 325. Print a Binary Tree in Vertical Order | Set 1
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
root->right->right->right = newNode(9);
cout << "Vertical order traversal is \n";
verticalOrder(root);
return 0;
}
Java
1932
Chapter 325. Print a Binary Tree in Vertical Order | Set 1
1933
Chapter 325. Print a Binary Tree in Vertical Order | Set 1
/* Let us construct the tree shown in above diagram */
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.right.left.right = new Node(8);
tree.root.right.right.right = new Node(9);
System.out.println("vertical order traversal is :");
tree.verticalOrder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal
Python
1934
Chapter 325. Print a Binary Tree in Vertical Order | Set 1
# A utility function to print all nodes on a given line_no
# hd is horizontal distance of current node with respect to root
def printVerticalLine(node, line_no, hd):
# Base Case
if node is None:
return
# If this node is on the given line number
if hd == line_no:
print node.data,
# Recur for left and right subtrees
printVerticalLine(node.left, line_no, hd-1)
printVerticalLine(node.right, line_no, hd+1)
def verticalOrder(root):
# Find min and max distances with respect to root
minimum = [0]
maximum = [0]
findMinMax(root, minimum, maximum, 0)
# Iterate through all possible lines starting
# from the leftmost line and print nodes line by line
for line_no in range(minimum[0], maximum[0]+1):
printVerticalLine(root, line_no, 0)
print
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right = Node(8)
root.right.right.right = Node(9)
print "Vertical order traversal is"
verticalOrder(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
1935
Chapter 325. Print a Binary Tree in Vertical Order | Set 1
Source
https://www.geeksforgeeks.org/print-binary-tree-vertical-order/
1936
Chapter 326
Print a Binary Tree in Vertical Order | Set 2 (Map based Method) - GeeksforGeeks
Given a binary tree, print it vertically. The following example illustrates vertical order
traversal.
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
1937
Chapter 326. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
We have discussed a O(n2 ) solution in the previous post. In this post, an efficient solution
based on hash map is discussed. We need to check the Horizontal Distances from root for
all nodes. If two nodes have the same Horizontal Distance (HD), then they are on same
vertical line. The idea of HD is simple. HD for root is 0, a right edge (edge connecting
to right subtree) is considered as +1 horizontal distance and a left edge is considered as -1
horizontal distance. For example, in the above tree, HD for Node 4 is at -2, HD for Node 2
is -1, HD for 5 and 6 is 0 and HD for node 7 is +2.
We can do preorder traversal of the given Binary Tree. While traversing the tree, we can
recursively calculate HDs. We initially pass the horizontal distance as 0 for root. For left
subtree, we pass the Horizontal Distance as Horizontal distance of root minus 1. For right
subtree, we pass the Horizontal Distance as Horizontal Distance of root plus 1. For every
HD value, we maintain a list of nodes in a hasp map. Whenever we see a node in traversal,
we go to the hash map entry and add the node to the hash map using HD as a key in map.
Following is C++ implementation of the above method. Thanks to Chirag for providing
the below C++ implementation.
1938
Chapter 326. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
C++
1939
Chapter 326. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
Java
1940
Chapter 326. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
// Constructor
Node(int data)
{
key = data;
left = null;
right = null;
}
}
// Utility function to store vertical order in map 'm'
// 'hd' is horizontal distance of current node from root.
// 'hd' is initially passed as 0
static void getVerticalOrder(Node root, int hd,
TreeMap<Integer,Vector<Integer>> m)
{
// Base case
if(root == null)
return;
//get the vector list at 'hd'
Vector<Integer> get = m.get(hd);
// Store current node in map 'm'
if(get == null)
{
get = new Vector<>();
get.add(root.key);
}
else
get.add(root.key);
m.put(hd, get);
// Store nodes in left subtree
getVerticalOrder(root.left, hd-1, m);
// Store nodes in right subtree
getVerticalOrder(root.right, hd+1, m);
}
// The main function to print vertical oder of a binary tree
// with given root
static void printVerticalOrder(Node root)
{
// Create a map and store vertical oder in map using
// function getVerticalOrder()
TreeMap<Integer,Vector<Integer>> m = new TreeMap<>();
1941
Chapter 326. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
int hd =0;
getVerticalOrder(root,hd,m);
// Traverse the map and print nodes at every horigontal
// distance (hd)
for (Entry<Integer, Vector<Integer>> entry : m.entrySet())
{
System.out.println(entry.getValue());
}
}
// Driver program to test above functions
public static void main(String[] args) {
// TO DO Auto-generated method stub
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
root.right.left.right = new Node(8);
root.right.right.right = new Node(9);
System.out.println("Vertical Order traversal is");
printVerticalOrder(root);
}
}
// This code is contributed by Sumit Ghosh
Python
1942
Chapter 326. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
1943
Chapter 326. Print a Binary Tree in Vertical Order | Set 2 (Map based Method)
Output:
Time Complexity of hashing based solution can be considered as O(n) under the assump-
tion that we have good hashing function that allows insertion and retrieval operations in
O(1) time. In the above C++ implementation, map of STL is used. map in STL is typically
implemented using a Self-Balancing Binary Search Tree where all operations take O(Logn)
time. Therefore time complexity of above implementation is O(nLogn).
Note that the above solution may print nodes in same vertical order as they
appear in tree. For example, the above program prints 12 before 9. See this for a sample
run.
1
/
2 3
/ /
4 5 6 7
/
8 10 9
11
12
Refer below post for level order traversal based solution. The below post makes sure that
nodes of a vertical line are printed in same order as they appear in tree.
Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
Source
https://www.geeksforgeeks.org/print-binary-tree-vertical-order-set-2/
1944
Chapter 327
Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal) - GeeksforGeeks
Given a binary tree, print it vertically. The following example illustrates vertical order
traversal.
1
/ \
2 3
/ \ / \
4 5 6 7
\ \
8 9
1945
Chapter 327. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
1
/ \
2 3
/ \ / \
4 5 6 7
\ / \
8 10 9
1946
Chapter 327. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
\
11
\
12
If we use level order traversal, we can make sure that if a node like 12 comes below in same
vertical line, it is printed after a node like 9 which comes above in vertical line.
C++
1947
Chapter 327. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
1948
Chapter 327. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
Python3
1949
Chapter 327. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
hd_node[root] = 0
m[0] = [root.data]
# loop will run while queue is not empty
while len(queue) > 0:
# dequeue node from queue
temp = queue.pop(0)
if temp.left:
# Enqueue left child
queue.append(temp.left)
# Store the horizontal distance of left node
# hd(left child) = hd(parent) -1
hd_node[temp.left] = hd_node[temp] - 1
hd = hd_node[temp.left]
if m.get(hd) is None:
m[hd] = []
m[hd].append(temp.left.data)
if temp.right:
# Enqueue right child
queue.append(temp.right)
# store the horizontal distance of right child
# hd(right child) = hd(parent) + 1
hd_node[temp.right] = hd_node[temp] + 1
hd = hd_node[temp.right]
if m.get(hd) is None:
m[hd] = []
m[hd].append(temp.right.data)
# Sort the map according to horizontal distance
sorted_m = collections.OrderedDict(sorted(m.items()))
# Traverse the sorted map and print nodes at each horizontal distance
for i in sorted_m.values():
for j in i:
print(j, " ", end="")
print()
# Driver program to check above function
1950
Chapter 327. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
"""
Constructed binary tree is
1
/ \
2 3
/ \ / \
4 5 6 7
\ / \
8 10 9
\
11
\
12
"""
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right =Node(8)
root.right.right.left = Node(10)
root.right.right.right = Node(9)
root.right.right.left.right = Node(11)
root.right.right.left.right.right = Node(12)
print("Vertical order traversal is ")
verticalTraverse(root)
# This code is contributed by Shweta Singh
Output:
Time Complexity of above implementation is O(n Log n). Note that above implementation
uses map which is implemented using self-balancing BST.
We can reduce time complexity to O(n) using unordered_map. To print nodes in desired
order, we can have 2 variables denoting min and max horizontal distance. We can simply
1951
Chapter 327. Print a Binary Tree in Vertical Order | Set 3 (Using Level Order Traversal)
iterate from min to max horizontal distance and get corresponding values from Map. So it
is O(n)
Auxiliary Space : O(n)
Improved By : shweta44
Source
https://www.geeksforgeeks.org/print-a-binary-tree-in-vertical-order-set-3-using-level-order-traversal/
1952
Chapter 328
Input : 10
/ \
8 2
/ \ /
3 5 7
Output : 10 8
Input : 1
/ \
2 3
/ \
4 6
Output : 1 3
This is a simple problem. We do any of the traversals (Inorder, Preorder, Postorder, level
order traversal) and keep printing nodes that have mode left and right children as non-NULL.
1953
Chapter 328. Print all full nodes in a Binary Tree
struct Node
{
int data;
struct Node *left, *right;
};
Node *newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Traverses given tree in Inorder fashion and
// prints all nodes that have both children as
// non-empty.
void findFullNode(Node *root)
{
if (root != NULL)
{
findFullNode(root->left);
if (root->left != NULL && root->right != NULL)
cout << root->data << " ";
findFullNode(root->right);
}
}
// Driver program to test above function
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(6);
root->right->left->right = newNode(7);
root->right->right->right = newNode(8);
root->right->left->right->left = newNode(9);
findFullNode(root);
return 0;
}
Output:
1 3
1954
Chapter 328. Print all full nodes in a Binary Tree
Source
https://www.geeksforgeeks.org/print-full-nodes-binary-tree/
1955
Chapter 329
Input : k = 5
Root of below binary tree:
1
/ \
3 -1
/ \ / \
2 1 4 5
/ / \ \
1 1 2 6
Output :
3 2
3 1 1
1 3 1
4 1
1 -1 4 1
-1 4 2
5
1 -1 5
1956
Chapter 329. Print all k-sum paths in a binary tree
1957
Chapter 329. Print all k-sum paths in a binary tree
1958
Chapter 329. Print all k-sum paths in a binary tree
int k = 5;
printKPath(root, k);
return 0;
}
Output:
3 2
3 1 1
1 3 1
4 1
1 -1 4 1
-1 4 2
5
1 -1 5
Source
https://www.geeksforgeeks.org/print-k-sum-paths-binary-tree/
1959
Chapter 330
Print all leaf nodes of a Binary Tree from left to right - GeeksforGeeks
Given a binary tree, we need to write a program to print all leaf nodes of the given binary
tree from left to right. That is, the nodes should be printed in the order they appear from
left to right in the given tree.
For Example,
4 6 7 9 10
The idea to do this is similar to DFS algorithm. Below is step by step algorithm to do this:
1. Check if given node is null. If null, then return from the function.
1960
Chapter 330. Print all leaf nodes of a Binary Tree from left to right
2. Check if it is a leaf node. If the node is a leaf node, then print its data.
3. If in above step, node is not a leaf node then check if left and right childs of node
exists. If yes then call function for left and right childs of the node recursively.
1961
Chapter 330. Print all leaf nodes of a Binary Tree from left to right
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in
// above diagram
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->left = newNode(5);
root->right->right = newNode(8);
root->right->left->left = newNode(6);
root->right->left->right = newNode(7);
root->right->right->left = newNode(9);
root->right->right->right = newNode(10);
// print leaf nodes of the given tree
printLeafNodes(root);
return 0;
}
Output:
4 6 7 9 10
Source
https://www.geeksforgeeks.org/print-leaf-nodes-left-right-binary-tree/
1962
Chapter 331
1963
Chapter 331. Print all nodes at distance k from a given node
2) Other nodes, may be an ancestor of target, or a node in some other subtree. For target
node 8 and k is 2, the node 22 comes in this category.
Finding the first type of nodes is easy to implement. Just traverse subtrees rooted with
the target node and decrement k in recursive call. When the k becomes 0, print the node
currently being traversed (See thisfor more details). Here we call the function as printkdis-
tanceNodeDown().
How to find nodes of second type? For the output nodes not lying in the subtree with the
target node as the root, we must go through all ancestors. For every ancestor, we find its
distance from target node, let the distance be d, now we go to other subtree (if target was
found in left subtree, then we go to right subtree and vice versa) of the ancestor and find
all nodes at k-d distance from the ancestor.
Following is the implementation of the above approach.
C++
#include <iostream>
using namespace std;
// A binary Tree node
struct node
{
int data;
struct node *left, *right;
};
/* Recursive function to print all the nodes at distance k in the
tree (or subtree) rooted with given root. See */
void printkdistanceNodeDown(node *root, int k)
{
// Base Case
if (root == NULL || k < 0) return;
// If we reach a k distant node, print it
if (k==0)
{
cout << root->data << endl;
return;
}
// Recur for left and right subtrees
printkdistanceNodeDown(root->left, k-1);
printkdistanceNodeDown(root->right, k-1);
}
// Prints all nodes at distance k from a given target node.
// The k distant nodes may be upward or downward. This function
// Returns distance of root from target node, it returns -1 if target
1964
Chapter 331. Print all nodes at distance k from a given node
1965
Chapter 331. Print all nodes at distance k from a given node
return -1;
}
// A utility function to create a new binary tree node
node *newnode(int data)
{
node *temp = new node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
/* Let us construct the tree shown in above diagram */
node * root = newnode(20);
root->left = newnode(8);
root->right = newnode(22);
root->left->left = newnode(4);
root->left->right = newnode(12);
root->left->right->left = newnode(10);
root->left->right->right = newnode(14);
node * target = root->left->right;
printkdistanceNode(root, target, 2);
return 0;
}
Java
1966
Chapter 331. Print all nodes at distance k from a given node
1967
Chapter 331. Print all nodes at distance k from a given node
1968
Chapter 331. Print all nodes at distance k from a given node
Python
1969
Chapter 331. Print all nodes at distance k from a given node
return -1
# If target is same as root. Use the downward function
# to print all nodes at distance k in subtree rooted with
# target or root
if root == target:
printkDistanceNodeDown(root, k)
return 0
# Recur for left subtree
dl = printkDistanceNode(root.left, target, k)
# Check if target node was found in left subtree
if dl != -1:
# If root is at distance k from target, print root
# Note: dl is distance of root's left child
# from target
if dl +1 == k :
print root.data
# Else go to right subtreee and print all k-dl-2
# distant nodes
# Note: that the right child is 2 edges away from
# left chlid
else:
printkDistanceNodeDown(root.right, k-dl-2)
# Add 1 to the distance and return value for
# for parent calls
return 1 + dl
# MIRROR OF ABOVE CODE FOR RIGHT SUBTREE
# Note that we reach here only when node was not found
# in left subtree
dr = printkDistanceNode(root.right, target, k)
if dr != -1:
if (dr+1 == k):
print root.data
else:
printkDistanceNodeDown(root.left, k-dr-2)
return 1 + dr
# If target was neither present in left nor in right subtree
return -1
# Driver program to test above function
root = Node(20)
1970
Chapter 331. Print all nodes at distance k from a given node
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(4)
root.left.right = Node(12)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
target = root.left.right
printkDistanceNode(root, target, 2)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
4
20
Time Complexity: At first look the time complexity looks more than O(n), but if we take a
closer look, we can observe that no node is traversed more than twice. Therefore the time
complexity is O(n).
This article is contributed by Prasant Kumar. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : HarshitGargjpr, zoozoo
Source
https://www.geeksforgeeks.org/print-nodes-distance-k-given-node-binary-tree/
1971
Chapter 332
Examples :
1972
Chapter 332. Print all nodes in a binary tree having K leaves
Input : k = 1
Output: {6}
// here node 6 have k = 1 leave
Here any node having K leaves means sum of leaves in left subtree and in right subtree
must be equal to K. So to solve this problem we use Postorder traversal of tree. First we
calculate leaves in left subtree then in right subtree and if sum is equal to K, then print
current node. In each recursive call we return sum of leaves of left subtree and right subtree
to it’s ancestor.
1973
Chapter 332. Print all nodes in a binary tree having K leaves
kLeaves(ptr->right, k);
// Print this node if total is k
if (k == total)
cout << ptr->data << " ";
return total;
}
// Driver program to run the case
int main()
{
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(4);
root->left->left = newNode(5);
root->left->right = newNode(6);
root->left->left->left = newNode(9);
root->left->left->right = newNode(10);
root->right->right = newNode(8);
root->right->left = newNode(7);
root->right->left->left = newNode(11);
root->right->left->right = newNode(12);
kLeaves(root, 2);
return 0;
}
Output:
5 7
Source
https://www.geeksforgeeks.org/print-nodes-binary-tree-k-leaves/
1974
Chapter 333
Print all nodes that are at distance k from a leaf node - GeeksforGeeks
Given a Binary Tree and a positive integer k, print all nodes that are distance k from a leaf
node.
Here the meaning of distance is different from previous post. Here k distance from a leaf
means k levels higher than a leaf node. For example if k is more than height of Binary Tree,
then nothing should be printed. Expected time complexity is O(n) where n is the number
nodes in the given Binary Tree.
The idea is to traverse the tree. Keep storing all ancestors till we hit a leaf node. When we
reach a leaf node, we print the ancestor at distance k. We also need to keep track of nodes
that are already printed as output. For that we use a boolean array visited[].
C++
1975
Chapter 333. Print all nodes that are at distance k from a leaf node
1976
Chapter 333. Print all nodes that are at distance k from a leaf node
}
/* Given a binary tree and a nuber k, print all nodes that are k
distant from a leaf*/
void printKDistantfromLeaf(Node* node, int k)
{
int path[MAX_HEIGHT];
bool visited[MAX_HEIGHT] = {false};
kDistantFromLeafUtil(node, path, visited, 0, k);
}
/* Driver program to test above functions*/
int main()
{
// Let us create binary tree given in the above example
Node * root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
cout << "Nodes at distance 2 are: ";
printKDistantfromLeaf(root, 2);
return 0;
}
Java
1977
Chapter 333. Print all nodes that are at distance k from a leaf node
Node root;
/* This function prints all nodes that are distance k from a leaf node
path[] --> Store ancestors of a node
visited[] --> Stores true if a node is printed as output. A node may
be k distance away from many leaves, we want to print it once */
void kDistantFromLeafUtil(Node node, int path[], boolean visited[],
int pathLen, int k)
{
// Base case
if (node == null)
return;
/* append this Node to the path array */
path[pathLen] = node.data;
visited[pathLen] = false;
pathLen++;
/* it's a leaf, so print the ancestor at distance k only
if the ancestor is not already printed */
if (node.left == null && node.right == null
&& pathLen - k - 1 >= 0 && visited[pathLen - k - 1] == false)
{
System.out.print(path[pathLen - k - 1] + " ");
visited[pathLen - k - 1] = true;
return;
}
/* If not leaf node, recur for left and right subtrees */
kDistantFromLeafUtil(node.left, path, visited, pathLen, k);
kDistantFromLeafUtil(node.right, path, visited, pathLen, k);
}
/* Given a binary tree and a nuber k, print all nodes that are k
distant from a leaf*/
void printKDistantfromLeaf(Node node, int k)
{
int path[] = new int[1000];
boolean visited[] = new boolean[1000];
kDistantFromLeafUtil(node, path, visited, 0, k);
}
// Driver program to test the above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
/* Let us construct the tree shown in above diagram */
1978
Chapter 333. Print all nodes that are at distance k from a leaf node
Output:
Time Complexity: Time Complexity of above code is O(n) as the code does a simple tree
traversal.
Source
https://www.geeksforgeeks.org/print-nodes-distance-k-leaf-node/
1979
Chapter 334
This is a typical tree traversal question. We start from root and check if the node has one
child, if yes then print the only child of that node. If node has both children, then recur for
both the children.
C++
1980
Chapter 334. Print all nodes that don’t have sibling
1981
Chapter 334. Print all nodes that don’t have sibling
printSingles(root->left);
}
}
// Driver program to test above functions
int main()
{
// Let us create binary tree given in the above example
node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(5);
root->right->left->left = newNode(6);
printSingles(root);
return 0;
}
Java
1982
Chapter 334. Print all nodes that don’t have sibling
Python
1983
Chapter 334. Print all nodes that don’t have sibling
Output:
4 5 6
Time Complexity of above code is O(n) as the code does a simple tree traversal.
1984
Chapter 334. Print all nodes that don’t have sibling
This article is compiled by Aman Gupta. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/print-nodes-dont-sibling-binary-tree/
1985
Chapter 335
Print all root to leaf paths with there relative positions - GeeksforGeeks
Given a binary tree, print the root to the leaf path, but add “_” to indicate the relative
position.
Example:
_ A
B
_ E
A
_ C
F
A
_ C
_ _ G
1986
Chapter 335. Print all root to leaf paths with there relative positions
……a) First find the minimum Horizontal distance of the current path.
……b) After that we traverse current path
……….First Print number of underscore “_” : abs (current_node_HD – minimum-HD)
……….Print current node value.
We do this process for all root to leaf path
Bellow is C++ implementations of above idea.
1987
Chapter 335. Print all root to leaf paths with there relative positions
1988
Chapter 335. Print all root to leaf paths with there relative positions
1989
Chapter 335. Print all root to leaf paths with there relative positions
Output:
_ _ A
_ B
D
==============================
_ A
B
_ E
==============================
A
_ C
F
==============================
A
_ C
_ _ G
Source
https://www.geeksforgeeks.org/print-all-root-to-leaf-paths-with-there-relative-positions/
1990
Chapter 336
Print all the paths from root, with a specified sum in Binary tree - GeeksforGeeks
Given a Binary tree and a sum S, print all the paths, starting from root, that sums upto
the given sum.
Note that this problem is different from root to leaf paths. Here path doesn’t need to end
on a leaf node.
Examples:
Input :
Input : sum = 8,
Root of tree
1
/ \
20 3
/ \
4 15
/ \ / \
6 7 8 9
Output :
Path: 1 3 4
1991
Chapter 336. Print all the paths from root, with a specified sum in Binary tree
28 13
/ \
14 15
/ \ / \
21 22 23 24
Output : Path found: 10 28
Path found: 10 13 15
For this problem, preorder traversal is best suited as we have to add up a key value as we
land on that node.
We start from the root and start traversing by preorder traversal, adding key value to the
sum_so_far and checking whether it is equal to the required sum.
Also, as tree node doesn’t have a pointer pointing to its parent, we have to explicitly save
from where we have moved. We use a vector path to store the path for this.
Every node in this path contributes to the sum_so_far.
1992
Chapter 336. Print all the paths from root, with a specified sum in Binary tree
1993
Chapter 336. Print all the paths from root, with a specified sum in Binary tree
root->right->left = newNode(14);
root->right->right = newNode(15);
root->right->left->left = newNode(21);
root->right->left->right = newNode(22);
root->right->right->left = newNode(23);
root->right->right->right = newNode(24);
int sum = 38;
printPaths(root, sum);
return 0;
}
Output:
Path found: 10 28
Path found: 10 13 15
Source
https://www.geeksforgeeks.org/print-paths-root-specified-sum-binary-tree/
1994
Chapter 337
Print common nodes on path from root (or common ancestors) - GeeksforGeeks
Given a binary tree and two nodes, the task is to Print all the nodes that are common for
2 given nodes in a binary tree.
Examples:
Asked in : Amazon
C/C++
1995
Chapter 337. Print common nodes on path from root (or common ancestors)
1996
Chapter 337. Print common nodes on path from root (or common ancestors)
// Utility Function to print all ancestors of LCA
bool printAncestors(struct Node* root, int target)
{
/* base cases */
if (root == NULL)
return false;
if (root->key == target) {
cout << root->key << " ";
return true;
}
/* If target is present in either left or right
subtree of this node, then print this node */
if (printAncestors(root->left, target) ||
printAncestors(root->right, target)) {
cout << root->key << " ";
return true;
}
/* Else return false */
return false;
}
// Function to find nodes common to given two nodes
bool findCommonNodes(struct Node* root, int first,
int second)
{
struct Node* LCA = findLCA(root, first, second);
if (LCA == NULL)
return false;
printAncestors(root, LCA->key);
}
// Driver program to test above functions
int main()
{
// Let us create binary tree given in the above
// example
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
1997
Chapter 337. Print common nodes on path from root (or common ancestors)
root->left->left->left = newNode(8);
root->right->left->left = newNode(9);
root->right->left->right = newNode(10);
if (findCommonNodes(root, 9, 7) == false)
cout << "No Common nodes";
return 0;
}
Java
1998
Chapter 337. Print common nodes on path from root (or common ancestors)
1999
Chapter 337. Print common nodes on path from root (or common ancestors)
return true;
}
// Driver program to test above functions
public static void main(String args[])
{
/*Let us create Binary Tree shown in
above example */
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.left.left.left = new Node(8);
tree.root.right.left.left = new Node(9);
tree.root.right.left.right = new Node(10);
if (findCommonNodes(root, 9, 7) == false)
System.out.println("No Common nodes");
}
}
// This code is contributed by Mr Somesh Awasthi
Output:
3 1
Source
https://www.geeksforgeeks.org/print-common-nodes-path-root-common-ancestors/
2000
Chapter 338
Output : 6, 7
The idea to first find level of given node using the approach discussed here. Once we have
found level, we can print all nodes at a given level using the approach discussed here. The
only thing to take care of is, sibling should not be printed. To handle this, we change the
printing function to first check for sibling and print node only if it is not sibling.
Below is C++ implementation of above idea.
2001
Chapter 338. Print cousins of a given node in Binary Tree
struct Node
{
int data;
Node *left, *right;
};
// A utility function to create a new Binary
// Tree Node
Node *newNode(int item)
{
Node *temp = new Node;
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
/* It returns level of the node if it is present
in tree, otherwise returns 0.*/
int getLevel(Node *root, Node *node, int level)
{
// base cases
if (root == NULL)
return 0;
if (root == node)
return level;
// If node is present in left subtree
int downlevel = getLevel(root->left, node, level+1);
if (downlevel != 0)
return downlevel;
// If node is not present in left subtree
return getLevel(root->right, node, level+1);
}
/* Print nodes at a given level such that sibling of
node is not printed if it exists */
void printGivenLevel(Node* root, Node *node, int level)
{
// Base cases
if (root == NULL || level < 2)
return;
// If current node is parent of a node with
// given level
if (level == 2)
{
if (root->left == node || root->right == node)
2002
Chapter 338. Print cousins of a given node in Binary Tree
return;
if (root->left)
printf("%d ", root->left->data);
if (root->right)
printf("%d ", root->right->data);
}
// Recur for left and right subtrees
else if (level > 2)
{
printGivenLevel(root->left, node, level-1);
printGivenLevel(root->right, node, level-1);
}
}
// This function prints cousins of a given node
void printCousins(Node *root, Node *node)
{
// Get level of given node
int level = getLevel(root, node, 1);
// Print nodes of given level.
printGivenLevel(root, node, level);
}
// Driver Program to test above functions
int main()
{
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->right->right = newNode(15);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
printCousins(root, root->left->right);
return 0;
}
Output :
6 7
2003
Chapter 338. Print cousins of a given node in Binary Tree
Can we solve this problem using single traversal? Please refer below article
Print cousins of a given node in Binary Tree | Single Traversal
Source
https://www.geeksforgeeks.org/print-cousins-of-a-given-node-in-binary-tree/
2004
Chapter 339
Output : 6, 7
Note that it is the same problem as given at Print cousins of a given node in Binary Tree
which consists of two traversals recursively. In this post, a single level traversal approach is
discussed.
The idea is to go for level order traversal of the tree, as the cousins and siblings of a node
can be found in its level order traversal. Run the traversal till the level containing the node
is not found, and if found, print the given level.
How to print the cousin nodes instead of siblings and how to get the nodes of
that level in the queue? During the level order, when for the parent node, if parent->left
== Node_to_find, or parent->right == Node_to_find, then the children of this parent
must not be pushed into the queue (as one is the node and other will be its sibling). Push
the remaining nodes at the same level in the queue and then exit the loop. The current
2005
Chapter 339. Print cousins of a given node in Binary Tree | Single Traversal
queue will have the nodes at the next level (the level of the node being searched, except the
node and its sibling). Now, print the queue.
Following is the implementation of the above algorithm.
C++
2006
Chapter 339. Print cousins of a given node in Binary Tree | Single Traversal
2007
Chapter 339. Print cousins of a given node in Binary Tree | Single Traversal
return;
}
// Driver Program to test above function
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->right->right = newNode(15);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
Node* x = newNode(43);
printCousins(root, x);
printCousins(root, root);
printCousins(root, root->right);
printCousins(root, root->left);
printCousins(root, root->left->right);
return 0;
}
Java
2008
Chapter 339. Print cousins of a given node in Binary Tree | Single Traversal
class GFG
{
// function to print
// cousins of the node
static void printCousins(Node root,
Node node_to_find)
{
// if the given node
// is the root itself,
// then no nodes would
// be printed
if (root == node_to_find)
{
System.out.print("Cousin Nodes :" +
" None" + "\n");
return;
}
Queue<Node> q = new LinkedList<Node>();
boolean found = false;
int size_ = 0;
Node p = null;
q.add(root);
// the following loop runs
// until found is not true,
// or q is not empty. if
// found has become true => we
// have found the level in
// which the node is present
// and the present queue will
// contain all the cousins of
// that node
while (q.isEmpty() == false &&
found == false)
{
size_ = q.size();
while (size_ -- > 0)
{
p = q.peek();
q.remove();
// if current node's left
// or right child is the
// same as the node to find,
// then make found = true,
2009
Chapter 339. Print cousins of a given node in Binary Tree | Single Traversal
2010
Chapter 339. Print cousins of a given node in Binary Tree | Single Traversal
return;
}
// Driver code
public static void main(String[] args)
{
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.left.right.right = new Node(15);
root.right.left = new Node(6);
root.right.right = new Node(7);
root.right.left.right = new Node(8);
Node x = new Node(43);
printCousins(root, x);
printCousins(root, root);
printCousins(root, root.right);
printCousins(root, root.left);
printCousins(root, root.left.right);
}
}
Output:
Time Complexity : This is a single level order traversal, hence time complexity = O(n), and
Auxiliary space = O(n) (See this).
Source
https://www.geeksforgeeks.org/print-cousins-of-a-given-node-in-binary-tree-single-traversal/
2011
Chapter 340
Print extreme nodes of each level of Binary Tree in alternate order - GeeksforGeeks
Given a binary tree, print nodes of extreme corners of each level but in alternate order.
Example:
2012
Chapter 340. Print extreme nodes of each level of Binary Tree in alternate order
1 3 4 15 16
– print leftmost node of 1st level
– print rightmost node of 2nd level
– print leftmost node of 3rd level
– print rightmost node of 4th level
– print leftmost node of 5th level
The idea is to traverse tree level by level. For each level, we count number of nodes in it
and print its leftmost or the rightmost node based on value of a Boolean flag. We dequeue
all nodes of current level and enqueue all nodes of next level and invert value of Boolean
flag when switching levels.
Below is C++ implementation of above idea –
2013
Chapter 340. Print extreme nodes of each level of Binary Tree in alternate order
2014
Chapter 340. Print extreme nodes of each level of Binary Tree in alternate order
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->left->left->right = newNode(9);
root->left->right->left = newNode(10);
root->left->right->right = newNode(11);
root->right->right->left = newNode(14);
root->right->right->right = newNode(15);
root->left->left->left->left = newNode(16);
root->left->left->left->right = newNode(17);
root->right->right->right->right = newNode(31);
printExtremeNodes(root);
return 0;
}
Output:
1 2 7 8 31
Time complexity of above solution is O(n) where n is total number of nodes in given
binary tree.
Exercise – Print nodes of extreme corners of each level from bottom to top in alternate
order.
Source
https://www.geeksforgeeks.org/print-extreme-nodes-of-each-level-of-binary-tree-in-alternate-order/
2015
Chapter 341
A Simple Solution is to do two traversals using the approaches discussed for printing left
view and right view.
Can we print all corner nodes using one traversal?
The idea is to use Level Order Traversal. To find first node, we use a variable isFirst. To
separate levels, we enqueue NULL after every level. So in level order traversal, if we see a
NULL, we know next node would be first node of its level and therefore we set isFirst.
A special case to consider is, a tree like below.
1
\
2016
Chapter 341. Print leftmost and rightmost nodes of a Binary Tree
2
\
3
The output for above tree should be 1, 2, 3. We need make sure that the levels having only
one node are handled and the node is printed only once. For this purpose, we maintain a
separate variable isOne.
C++
2017
Chapter 341. Print leftmost and rightmost nodes of a Binary Tree
2018
Chapter 341. Print leftmost and rightmost nodes of a Binary Tree
// Here we are making isOne = false to signify
// that level has more than one node
isOne = false;
if (temp->left)
q.push(temp->left);
if (temp->right)
q.push(temp->right);
}
}
}
// Driver program to test above function
int main ()
{
Node *root = newNode(15);
root->left = newNode(10);
root->right = newNode(20);
root->left->left = newNode(8);
root->left->right = newNode(12);
root->right->left = newNode(16);
root->right->right = newNode(25);
printCorner(root);
return 0;
}
Java
2019
Chapter 341. Print leftmost and rightmost nodes of a Binary Tree
Node root;
/* Function to print corner node at each level */
void printCorner(Node root)
{
// star node is for keeping track of levels
Queue<Node> q = new LinkedList<Node>();
// pushing root node and star node
q.add(root);
q.add(null);
// if isFirst = true then left most node of that level
// will be printed
boolean isFirst = false;
// if isOne = true then that level has only one node
boolean isOne = false;
// last will store right most node of that level
int last = 0;
// Do level order traversal of Binary Tree
while (!q.isEmpty())
{
// dequeue the front node from the queue
Node temp = q.peek();
q.poll();
// if isFirst is true, then temp is leftmost node
if (isFirst)
{
System.out.print(temp.key + " ");
if (temp.left != null)
q.add(temp.left);
if (temp.right != null)
q.add(temp.right);
// make isFirst as false and one = 1
isFirst = false;
isOne = true;
}
// Else if temp is a separator between two levels
else if (temp == null)
{
// Insert new separator if there are items in queue
2020
Chapter 341. Print leftmost and rightmost nodes of a Binary Tree
Output :
2021
Chapter 341. Print leftmost and rightmost nodes of a Binary Tree
15 10 20 8 25
Source
https://www.geeksforgeeks.org/print-leftmost-and-rightmost-nodes-of-a-binary-tree/
2022
Chapter 342
Example 1:
Example 2:
1
/ \
2 3
/ \\
4 5 6
/ \ /
7 8 9
Output for above tree should be
1
2 3
4 5 6
7 8 9<
2023
Chapter 342. Print level order traversal line by line | Set 1
Note that this is different fromsimple level order traversal where we need to print all nodes
together. Here we need to print nodes of different levels in different lines.
A simple solution is to print use the recursive function discussed in the level order traversal
post and print a new line after every call to printGivenLevel().
C++
Java
2024
Chapter 342. Print level order traversal line by line | Set 1
2025
Chapter 342. Print level order traversal line by line | Set 1
2026
Chapter 342. Print level order traversal line by line | Set 1
Java
2027
Chapter 342. Print level order traversal line by line | Set 1
Output:
1
2 3
4 5 6
Time complexity of this method is O(n) where n is number of nodes in given binary tree.
2028
Chapter 342. Print level order traversal line by line | Set 1
Source
https://www.geeksforgeeks.org/print-level-order-traversal-line-line/
2029
Chapter 343
Print middle level of perfect binary tree without finding height - GeeksforGeeks
Given a perfect binary tree, print nodes of middle level without computing its height. A
perfect binary tree is a binary tree in which all interior nodes have two children and all
leaves have the same depth or same level.
Output : 4 5 6 7
The idea is similar to method 2 of finding middle of singly linked list.
Use fast and slow (or tortoise) pointers in each route of a the tree.
1. Advance fast pointer towards leaf by 2.
2. Advance slow pointer towards lead by 1.
3. If fast pointer reaches the leaf print value at slow pointer
4. Call recursively the next route.
2030
Chapter 343. Print middle level of perfect binary tree without finding height
C++
#include <bits/stdc++.h>
using namespace std;
/* A binary tree node has key, pointer to left
child and a pointer to right child */
struct Node
{
int key;
struct Node* left, *right;
};
/* To create a newNode of tree and return pointer */
struct Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
// Takes two parameters - same initially and
// calls recursively
void printMiddleLevelUtil(Node* a, Node* b)
{
// Base case e
if (a == NULL || b == NULL)
return;
// Fast pointer has reached the leaf so print
// value at slow pointer
if ((b->left == NULL) && (b->right == NULL))
{
cout << a->key << " ";
return;
}
// Recursive call
// root.left.left and root.left.right will
// print same value
// root.right.left and root.right.right
// will print same value
// So we use any one of the condition
printMiddleLevelUtil(a->left, b->left->left);
printMiddleLevelUtil(a->right, b->left->left);
}
2031
Chapter 343. Print middle level of perfect binary tree without finding height
Java
2032
Chapter 343. Print middle level of perfect binary tree without finding height
{
// Takes two parameters - same initially and
// calls recursively
private static void printMiddleLevelUtil(Node a,
Node b)
{
// Base case e
if (a == null || b == null)
return;
// Fast pointer has reached the leaf so print
// value at slow pointer
if ((b.left == null) && (b.right == null))
{
System.out.print(a.key + " ");
return;
}
// Recursive call
// root.left.left and root.left.right will
// print same value
// root.right.left and root.right.right
// will print same value
// So we use any one of the condition
printMiddleLevelUtil(a.left, b.left.left);
printMiddleLevelUtil(a.right, b.left.left);
}
// Main printing method that take a Tree as input
public static void printMiddleLevel(Node node)
{
printMiddleLevelUtil(node, node);
}
public static void main(String[] args)
{
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
Node n6 = new Node(6);
Node n7 = new Node(7);
n2.left = n4;
n2.right = n5;
n3.left = n6;
n3.right = n7;
2033
Chapter 343. Print middle level of perfect binary tree without finding height
n1.left = n2;
n1.right = n3;
printMiddleLevel(n1);
}
}
Output:
2 3
Improved By : Prasad_Kshirsagar
Source
https://www.geeksforgeeks.org/print-middle-level-perfect-binary-tree-without-finding-height/
2034
Chapter 344
1
/ \
2 3
/ \ /
4 5 8
The problem can be solved using recursion. Thanks to eldho for suggesting the solution.
C
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
2035
Chapter 344. Print nodes at k distance from root
2036
Chapter 344. Print nodes at k distance from root
getchar();
return 0;
}
Java
2037
Chapter 344. Print nodes at k distance from root
1
/ \
2 3
/ \ /
4 5 8
*/
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(8);
tree.printKDistant(tree.root, 2);
}
}
// This code has been contributed by Mayank Jaiswal
Python
2038
Chapter 344. Print nodes at k distance from root
/ \ /
4 5 8
"""
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(8)
printKDistant(root, 2)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Source
https://www.geeksforgeeks.org/print-nodes-at-k-distance-from-root/
2039
Chapter 345
Input :
20
/ \
10 30
/ \ / \
5 15 25 40
/
12
and k = 3
Root is at level 1.
Output :
5 15 25 40
2040
Chapter 345. Print nodes at k distance from root | Iterative
/* binary tree
root is at level 1
20
/ \
10 30
/ \ / \
5 15 25 40
/
12 */
#include <bits/stdc++.h>
using namespace std;
// Node of binary tree
struct Node {
int data;
Node* left, * right;
};
// Function to add a new node
Node* newNode(int data)
{
Node* newnode = new Node();
newnode->data = data;
newnode->left = newnode->right = NULL;
}
// Function to print nodes of given level
bool printKDistant(Node* root, int klevel)
{
queue<Node*> q;
int level = 1;
bool flag = false;
q.push(root);
// extra NULL is pushed to keep track
// of all the nodes to be pushed before
// level is incremented by 1
q.push(NULL);
while (!q.empty()) {
Node* temp = q.front();
// print when level is equal to k
if (level == klevel && temp != NULL) {
flag = true;
cout << temp->data << " ";
}
q.pop();
2041
Chapter 345. Print nodes at k distance from root | Iterative
2042
Chapter 345. Print nodes at k distance from root | Iterative
Output:
data at level 1 : 20
data at level 2 : 10 30
data at level 3 : 5 15 25 40
data at level 6 :
Number exceeds total number of levels
Source
https://www.geeksforgeeks.org/print-nodes-k-distance-root-iterative/
2043
Chapter 346
Print nodes between two given level numbers of a binary tree - GeeksforGeeks
Given a binary tree and two level numbers ‘low’ and ‘high’, print nodes from level low to
level high.
Output:
8 22
4 12
10 14
A Simple Method is to first write a recursive function that prints nodes of a given level
number. Then call recursive function in a loop from low to high. Time complexity of this
2044
Chapter 346. Print nodes between two given level numbers of a binary tree
method is O(n2 )
We can print nodes in O(n) time using queue based iterative level order traversal. The
idea is to do simple queue based level order traversal. While doing inorder traversal, add a
marker node at the end. Whenever we see a marker node, we increase level number. If level
number is between low and high, then print nodes.
The following is the implementation of above idea.
C++
// A C++ program to print Nodes level by level berween given two levels.
#include <iostream>
#include <queue>
using namespace std;
/* A binary tree Node has key, pointer to left and right children */
struct Node
{
int key;
struct Node* left, *right;
};
/* Given a binary tree, print nodes from level number 'low' to level
number 'high'*/
void printLevels(Node* root, int low, int high)
{
queue <Node *> Q;
Node *marker = new Node; // Marker node to indicate end of level
int level = 1; // Initialize level number
// Enqueue the only first level node and marker node for end of level
Q.push(root);
Q.push(marker);
// Simple level order traversal loop
while (Q.empty() == false)
{
// Remove the front item from queue
Node *n = Q.front();
Q.pop();
// Check if end of level is reached
if (n == marker)
{
// print a new line and increment level number
cout << endl;
level++;
2045
Chapter 346. Print nodes between two given level numbers of a binary tree
// Check if marker node was last node in queue or
// level number is beyond the given upper limit
if (Q.empty() == true || level > high) break;
// Enqueue the marker for end of next level
Q.push(marker);
// If this is marker, then we don't need print it
// and enqueue its children
continue;
}
// If level is equal to or greater than given lower level,
// print it
if (level >= low)
cout << n->key << " ";
// Enqueue children of non-marker node
if (n->left != NULL) Q.push(n->left);
if (n->right != NULL) Q.push(n->right);
}
}
/* Helper function that allocates a new Node with the
given key and NULL left and right pointers. */
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return (temp);
}
/* Driver program to test above functions*/
int main()
{
// Let us construct the BST shown in the above figure
struct Node *root = newNode(20);
root->left = newNode(8);
root->right = newNode(22);
root->left->left = newNode(4);
root->left->right = newNode(12);
root->left->right->left = newNode(10);
root->left->right->right = newNode(14);
cout << "Level Order traversal between given two levels is";
printLevels(root, 2, 3);
2046
Chapter 346. Print nodes between two given level numbers of a binary tree
return 0;
}
Java
// Java program to print Nodes level by level between given two levels
import java.util.LinkedList;
import java.util.Queue;
/* A binary tree Node has key, pointer to left and right children */
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
/* Given a binary tree, print nodes from level number 'low' to level
number 'high'*/
void printLevels(Node node, int low, int high)
{
Queue<Node> Q = new LinkedList<>();
Node marker = new Node(4); // Marker node to indicate end of level
int level = 1; // Initialize level number
// Enqueue the only first level node and marker node for end of level
Q.add(node);
Q.add(marker);
// Simple level order traversal loop
while (Q.isEmpty() == false)
{
// Remove the front item from queue
Node n = Q.peek();
Q.remove();
2047
Chapter 346. Print nodes between two given level numbers of a binary tree
2048
Chapter 346. Print nodes between two given level numbers of a binary tree
Python
2049
Chapter 346. Print nodes between two given level numbers of a binary tree
# Check if marker node was last node in queue
# or level nubmer is beyond the given upper limit
if len(Q) == 0 or level > high:
break
# Enqueue the marker for end of next level
Q.append(marker)
# If this is marker, then we don't need print it
# and enqueue its children
continue
if level >= low:
print n.key,
# Enqueue children of non-marker node
if n.left is not None:
Q.append(n.left)
Q.append(n.right)
# Driver program to test the above function
root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(4)
root.left.right = Node(12)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
print "Level Order Traversal between given two levels is",
printLevels(root,2,3)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Time complexity of above method is O(n) as it does a simple level order traversal.
This article is contributed by Frank. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/given-binary-tree-print-nodes-two-given-level-numbers/
2050
Chapter 347
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
Output: Top view: 4 2 1 3 7
Input:
1
/ \
2 3
\
4
\
5
\
6
Output: Top view: 2 1 3 6
2051
Chapter 347. Print nodes in top view of Binary Tree | Set 2
The idea is to do something similar to Vertical Order Traversal. Like Vertical Order Traver-
sal, we need to group nodes of same horizontal distance together. We do a level order
traversal so that the topmost node at a horizontal node is visited before any other node of
same horizontal distance below it. A Map is used to map the horizontal distance of the
node with the node’s Data and vertical distance of the node.
Below is the implementation of the above approach:
2052
Chapter 347. Print nodes in top view of Binary Tree | Set 2
2053
Chapter 347. Print nodes in top view of Binary Tree | Set 2
Output:
Top View : 2 1 3 6
Source
https://www.geeksforgeeks.org/print-nodes-in-top-view-of-binary-tree-set-2/
2054
Chapter 348
Input : 1
/ \
2 3
/ \ / \
4 5 6 7
x = 5
Output : 1->2->5
Approach: Create a recursive function that traverses the different path in the binary tree
to find the required node x. If node x is present then it returns true and accumulates the
path nodes in some array arr[]. Else it returns false.
Following are the cases during the traversal:
2055
Chapter 348. Print path from root to a given node in a binary tree
This recursive function can be accessed from other function to check whether node x is
present or not and if it is present, then the path nodes can be accessed from arr[]. You can
define arr[] globally or pass its reference to the recursive function.
2056
Chapter 348. Print path from root to a given node in a binary tree
2057
Chapter 348. Print path from root to a given node in a binary tree
Output:
1->2->5
Time complexity: O(n) in worst case, where n is the number of nodes in the binary tree.
Source
https://www.geeksforgeeks.org/print-path-root-given-node-binary-tree/
2058
Chapter 349
6
/ \
3 5
/ \ \
2 5 4
/ \
7 4
We strongly recommend you to minimize your browser and try this yourself
first.
We can traverse tree iteratively (we have used iterative preorder). The question is, how to
extend the traversal to print root to leaf paths? The idea is to maintain a map to store
parent pointers of binary tree nodes. Now whenever we encounter a leaf node while doing
iterative preorder traversal, we can easily print root to leaf path using parent pointer. Below
is C++ implementation of this idea.
2059
Chapter 349. Print root to leaf paths without using recursion
// using recursion
#include <bits/stdc++.h>
using namespace std;
/* A binary tree */
struct Node
{
int data;
struct Node *left, *right;
};
/* Helper function that allocates a new node
with the given data and NULL left and right
pointers.*/
Node* newNode(int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return node;
}
/* Function to print root to leaf path for a leaf
using parent nodes stored in map */
void printTopToBottomPath(Node* curr,
map<Node*, Node*> parent)
{
stack<Node*> stk;
// start from leaf node and keep on pushing
// nodes into stack till root node is reached
while (curr)
{
stk.push(curr);
curr = parent[curr];
}
// Start popping nodes from stack and print them
while (!stk.empty())
{
curr = stk.top();
stk.pop();
cout << curr->data << " ";
}
cout << endl;
}
/* An iterative function to do preorder traversal
2060
Chapter 349. Print root to leaf paths without using recursion
2061
Chapter 349. Print root to leaf paths without using recursion
parent[current->left] = current;
nodeStack.push(current->left);
}
}
}
// Driver program to test above functions
int main()
{
/* Constructed binary tree is
10
/ \
8 2
/ \ /
3 5 2 */
Node* root = newNode(10);
root->left = newNode(8);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(5);
root->right->left = newNode(2);
printRootToLeaf(root);
return 0;
}
Output :
10 8 3
10 8 5
10 2 2
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/print-root-leaf-path-without-using-recursion/
2062
Chapter 350
2063
Chapter 350. Print the longest leaf to leaf path in a Binary tree
Examples:
Input: 1
/ \
2 3
/ \
4 5
2064
Chapter 350. Print the longest leaf to leaf path in a Binary tree
Output : 4 2 1 3
or 5 2 1 3
Input: 1
/ \
2 3
/ \ \
4 5 6
Output : 4 2 1 3 6
or 5 2 1 3 6
We have already discussed how to find the diameter of a binary tree.Diameter of a Binary
tree
We know that Diameter of a tree can be calculated by only using the height function because
the diameter of a tree is nothing but the maximum value of (left_height + right_height +
1) for each node.
Now for the node which has the maximum value of (left_height + right_height + 1), we
find the longest root to leaf path on the left side and similarly on the right side. Finally, we
print left side path, root and right side path.
Time Complexity is O(N). N is the number of nodes in the tree.
2065
Chapter 350. Print the longest leaf to leaf path in a Binary tree
2066
Chapter 350. Print the longest leaf to leaf path in a Binary tree
2067
Chapter 350. Print the longest leaf to leaf path in a Binary tree
Output:
9 8 4 2 5 6
Source
https://www.geeksforgeeks.org/print-longest-leaf-leaf-path-binary-tree/
2068
Chapter 351
Output 1 4 5 6
Method 1 (Recursive)
The idea is to pass initial level as odd and switch level flag in every recursive call. For every
node, if odd flag is set, then print it.
2069
Chapter 351. Print the nodes at odd levels of a tree
Output:
1 4 5
2070
Chapter 351. Print the nodes at odd levels of a tree
2071
Chapter 351. Print the nodes at odd levels of a tree
}
// Utility method to create a node
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Driver code
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printOddNodes(root);
return 0;
}
Output:
1 4 5
Source
https://www.geeksforgeeks.org/print-nodes-odd-levels-tree/
2072
Chapter 352
Print the path common to the two paths from the root to the two given nodes - Geeks-
forGeeks
Given a binary tree with distinct nodes(no two nodes have the same have data values). The
problem is to print the path common to the two paths from the root to the two given nodes
n1 and n2. If either of the nodes are not present then print “No Common Path”.
Examples:
Input : 1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
n1 = 4, n2 = 8
Output : 1->2
Path form root to n1:
1->2->4
Common Path:
2073
Chapter 352. Print the path common to the two paths from the root to the two given nodes
1->2
1. Find the LCA(Lowest Common Ancestor) of the two nodes n1 and n2. Refer this.
2. If LCA exits then print the path from the root to LCA. Refer this. Else print “No
Common Path”.
2074
Chapter 352. Print the path common to the two paths from the root to the two given nodes
2075
Chapter 352. Print the path common to the two paths from the root to the two given nodes
// Else return NULL
return NULL;
}
// function returns true if
// there is a path from root to
// the given node. It also populates
// 'arr' with the given path
bool hasPath(Node *root, vector<int>& arr, int x)
{
// if root is NULL
// there is no path
if (!root)
return false;
// push the node's value in 'arr'
arr.push_back(root->data);
// if it is the required node
// return true
if (root->data == x)
return true;
// else check whether there the required node lies in the
// left subtree or right subtree of the current node
if (hasPath(root->left, arr, x) ||
hasPath(root->right, arr, x))
return true;
// required node does not lie either in the
// left or right subtree of the current node
// Thus, remove current node's value from 'arr'
// and then return false;
arr.pop_back();
return false;
}
// function to print the path common
// to the two paths from the root
// to the two given nodes if the nodes
// lie in the binary tree
void printCommonPath(Node *root, int n1, int n2)
{
// vector to store the common path
vector<int> arr;
// LCA of node n1 and n2
2076
Chapter 352. Print the path common to the two paths from the root to the two given nodes
Output:
1->2
Time complexity: O(n), where n is the number of nodes in the binary tree.
2077
Chapter 352. Print the path common to the two paths from the root to the two given nodes
Source
https://www.geeksforgeeks.org/print-path-common-two-paths-root-two-given-nodes/
2078
Chapter 353
Approach :
2079
Chapter 353. Product of nodes at k-th level in a tree represented as string
C++
2080
Chapter 353. Product of nodes at k-th level in a tree represented as string
int main()
{
string tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
int k = 2;
cout << productAtKthLevel(tree, k);
return 0;
}
Java
2081
Chapter 353. Product of nodes at k-th level in a tree represented as string
// Driver program
public static void main(String[] args)
{
String tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
int k = 2;
System.out.println(productAtKthLevel(tree, k));
}
}
// This code is contributed
// by Smitha Dinesh Semwal.
Python3
# Python 3 implementation
# to find product of
# digits of elements
# at k-th level
# Function to find
# product of digits
# of elements at
# k-th level
def productAtKthLevel(tree, k):
level = -1
# Initialize result
product = 1
n = len(tree)
for i in range(0, n):
# increasing level number
if (tree[i] == '('):
level+=1
# decreasing level number
elif (tree[i] == ')'):
level-=1
else:
# check if current level is
# the desired level or not
if (level == k):
product *= (int(tree[i]) - int('0'))
2082
Chapter 353. Product of nodes at k-th level in a tree represented as string
# required product
return product
# Driver program
tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"
k = 2
print(productAtKthLevel(tree, k))
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# implementation to find
// product of digits of
// elements at k-th level
using System;
class GFG
{
// Function to find product
// of digits of elements
// at k-th level
static int productAtKthLevel(string tree,
int k)
{
int level = -1;
// Initialize result
int product = 1;
int n = tree.Length;
for (int i = 0; i < n; i++)
{
// increasing
// level number
if (tree[i] == '(')
level++;
// decreasing
// level number
else if (tree[i] == ')')
level--;
2083
Chapter 353. Product of nodes at k-th level in a tree represented as string
else
{
// check if current level is
// the desired level or not
if (level == k)
product *= (tree[i] - '0');
}
}
// required product
return product;
}
// Driver Code
static void Main()
{
string tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
int k = 2;
Console.WriteLine(productAtKthLevel(tree, k));
}
}
// This code is contributed by Sam007
PHP
<?php
// php implementation to find product of
// digits of elements at k-th level
// Function to find product of digits
// of elements at k-th level
function productAtKthLevel($tree, $k)
{
$level = -1;
$product = 1; // Initialize result
$n = strlen($tree);
for ($i = 0; $i < $n; $i++)
{
// increasing level number
if ($tree[$i] == '(')
$level++;
// decreasing level number
else if ($tree[$i] == ')')
2084
Chapter 353. Product of nodes at k-th level in a tree represented as string
$level--;
else
{
// check if current level is
// the desired level or not
if ($level == $k)
$product *= (ord($tree[$i]) -
ord('0'));
}
}
// required product
return $product;
}
// Driver Code
$tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
$k = 2;
echo productAtKthLevel($tree, $k);
//This code is contributed by mits
?>
Output:
72
Source
https://www.geeksforgeeks.org/product-nodes-k-th-level-tree-represented-string/
2085
Chapter 354
getLeafCount(node)
1) If node is NULL then return 0.
2) Else If left and right child nodes are NULL return 1.
3) Else recursively calculate leaf count of the tree using below formula.
Leaf count of a tree = Leaf count of left subtree +
Leaf count of right subtree
Example Tree
Leaf count for the above tree is 3.
Implementation:
2086
Chapter 354. Program to count leaf nodes in a binary tree
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Function to get the count of leaf nodes in a binary tree*/
unsigned int getLeafCount(struct node* node)
{
if(node == NULL)
return 0;
if(node->left == NULL && node->right==NULL)
return 1;
else
return getLeafCount(node->left)+
getLeafCount(node->right);
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/*Driver program to test above functions*/
int main()
{
/*create a tree*/
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
/*get leaf count of the above created tree*/
2087
Chapter 354. Program to count leaf nodes in a binary tree
Java
2088
Chapter 354. Program to count leaf nodes in a binary tree
Python
2089
Chapter 354. Program to count leaf nodes in a binary tree
Time & Space Complexities: Since this program is similar to traversal of tree, time
and space complexities will be same as Tree traversal (Please see our Tree Traversal post
for details)
Source
https://www.geeksforgeeks.org/write-a-c-program-to-get-count-of-leaf-nodes-in-a-binary-tree/
2090
Chapter 355
PruferCode = {}
The lowest label leaf is 2, we remove it from tree
and add the other vertex (connecting it to the tree)
to Prufer code
Tree now becomes
5
/ \
1 4
\
3
Prufer Code becomes = {1}
2091
Chapter 355. Prufer Code to Tree Creation
Input : (4, 1, 3, 4)
Output : Edges of following tree
2----4----3----1----5
|
6
Input : (1, 3, 5)
Output : Edges of following tree
2----1----3----5----4
Let the length of given Prufer code be m. The idea is to create an empty graph of m+2
vertices. We remove first element from sequence. Let first element of current sequence be x.
Then we find the least value which is not present in the given sequence and not yet added
to the tree. Let this value be be y. We add an edge from x to y and repeat this step.
Let us understand algorithm to construct tree with above first example:
Input : (4, 1, 3, 4)
2092
Chapter 355. Prufer Code to Tree Creation
2093
Chapter 355. Prufer Code to Tree Creation
Output:
2094
Chapter 355. Prufer Code to Tree Creation
Source
https://www.geeksforgeeks.org/prufer-code-tree-creation/
2095
Chapter 356
Quad Tree
Quadtrees are used in image compression, where each node contains the average colour of
each of its children. The deeper you traverse in the tree, the more the detail of the image.
Quadtrees are also used in searching for nodes in a two-dimensional area. For instance, if
you wanted to find the closest point to given coordinates, you can do it using quadtrees.
Insert Function
The insert functions is used to insert a node into an existing Quad Tree. This function first
checks whether the given node is within the boundaries of the current quad. If it is not, then
we immediately cease the insertion. If it is within the boundaries, we select the appropriate
child to contain this node based on its location.
This function is O(Log N) where N is the size of distance.
Search Function
The search function is used to locate a node in the given quad. It can also be modified to
return the closest node to the given point. This function is implemented by taking the given
point, comparing with the boundaries of the child quads and recursing.
This function is O(Log N) where N is size of distance.
The program given below demonstrates storage of nodes in a quadtree.
2096
Chapter 356. Quad Tree
#include <iostream>
#include <cmath>
using namespace std;
// Used to hold details of a point
struct Point
{
int x;
int y;
Point(int _x, int _y)
{
x = _x;
y = _y;
}
Point()
{
x = 0;
y = 0;
}
};
// The objects that we want stored in the quadtree
struct Node
{
Point pos;
int data;
Node(Point _pos, int _data)
{
pos = _pos;
data = _data;
}
Node()
{
data = 0;
}
};
// The main quadtree class
class Quad
{
// Hold details of the boundary of this node
Point topLeft;
Point botRight;
// Contains details of node
Node *n;
// Children of this tree
2097
Chapter 356. Quad Tree
Quad *topLeftTree;
Quad *topRightTree;
Quad *botLeftTree;
Quad *botRightTree;
public:
Quad()
{
topLeft = Point(0, 0);
botRight = Point(0, 0);
n = NULL;
topLeftTree = NULL;
topRightTree = NULL;
botLeftTree = NULL;
botRightTree = NULL;
}
Quad(Point topL, Point botR)
{
n = NULL;
topLeftTree = NULL;
topRightTree = NULL;
botLeftTree = NULL;
botRightTree = NULL;
topLeft = topL;
botRight = botR;
}
void insert(Node*);
Node* search(Point);
bool inBoundary(Point);
};
// Insert a node into the quadtree
void Quad::insert(Node *node)
{
if (node == NULL)
return;
// Current quad cannot contain it
if (!inBoundary(node->pos))
return;
// We are at a quad of unit area
// We cannot subdivide this quad further
if (abs(topLeft.x - botRight.x) <= 1 &&
abs(topLeft.y - botRight.y) <= 1)
{
if (n == NULL)
n = node;
2098
Chapter 356. Quad Tree
return;
}
if ((topLeft.x + botRight.x) / 2 >= node->pos.x)
{
// Indicates topLeftTree
if ((topLeft.y + botRight.y) / 2 >= node->pos.y)
{
if (topLeftTree == NULL)
topLeftTree = new Quad(
Point(topLeft.x, topLeft.y),
Point((topLeft.x + botRight.x) / 2,
(topLeft.y + botRight.y) / 2));
topLeftTree->insert(node);
}
// Indicates botLeftTree
else
{
if (botLeftTree == NULL)
botLeftTree = new Quad(
Point(topLeft.x,
(topLeft.y + botRight.y) / 2),
Point((topLeft.x + botRight.x) / 2,
botRight.y));
botLeftTree->insert(node);
}
}
else
{
// Indicates topRightTree
if ((topLeft.y + botRight.y) / 2 >= node->pos.y)
{
if (topRightTree == NULL)
topRightTree = new Quad(
Point((topLeft.x + botRight.x) / 2,
topLeft.y),
Point(botRight.x,
(topLeft.y + botRight.y) / 2));
topRightTree->insert(node);
}
// Indicates botRightTree
else
{
if (botRightTree == NULL)
botRightTree = new Quad(
Point((topLeft.x + botRight.x) / 2,
2099
Chapter 356. Quad Tree
2100
Chapter 356. Quad Tree
else
{
if (botRightTree == NULL)
return NULL;
return botRightTree->search(p);
}
}
};
// Check if current quadtree contains the point
bool Quad::inBoundary(Point p)
{
return (p.x >= topLeft.x &&
p.x <= botRight.x &&
p.y >= topLeft.y &&
p.y <= botRight.y);
}
// Driver program
int main()
{
Quad center(Point(0, 0), Point(8, 8));
Node a(Point(1, 1), 1);
Node b(Point(2, 5), 2);
Node c(Point(7, 6), 3);
center.insert(&a);
center.insert(&b);
center.insert(&c);
cout << "Node a: " <<
center.search(Point(1, 1))->data << "\n";
cout << "Node b: " <<
center.search(Point(2, 5))->data << "\n";
cout << "Node c: " <<
center.search(Point(7, 6))->data << "\n";
cout << "Non-existing node: "
<< center.search(Point(5, 5));
return 0;
}
Output:
Node a: 1
Node b: 2
Node c: 3
Non-existing node: 0
Exercise:
2101
Chapter 356. Quad Tree
Source
https://www.geeksforgeeks.org/quad-tree/
2102
Chapter 357
2103
Chapter 357. Queries for DFS of a subtree in a tree
In the above tree, if 1 is given as the node, then the DFS of subtree will be 1 2 4 6 7 5 3.
If 2 is given as the node, then the DFS of the subtree will be 2 4 6 7 5..
Approach:
2104
Chapter 357. Queries for DFS of a subtree in a tree
2105
Chapter 357. Queries for DFS of a subtree in a tree
{
// index of node in the original DFS
int ind = mp[node];
// height of subtree of node
int height = under[node];
cout << "The DFS of subtree " << node << ": ";
// print the DFS of subtree
for (int i = ind; i < ind + under[node]; i++) {
cout << a[i] << " ";
}
cout << endl;
}
// Function to add edges to a tree
void addEdge(int x, int y)
{
v[x].push_back(y);
v[y].push_back(x);
}
// Marks the index of node in original DFS
void markIndexDfs()
{
int size = a.size();
// marks the index
for (int i = 0; i < size; i++) {
mp[a[i]] = i;
}
}
// Driver Code
int main()
{
int n = 7;
// add edges of a tree
addEdge(1, 2);
addEdge(1, 3);
addEdge(2, 4);
addEdge(2, 5);
addEdge(4, 6);
addEdge(4, 7);
// array to store the height of subtree
2106
Chapter 357. Queries for DFS of a subtree in a tree
Source
https://www.geeksforgeeks.org/queries-for-dfs-of-a-subtree-in-a-tree/
2107
Chapter 358
2108
Chapter 358. Queries for M-th node in the DFS of subtree
Input: M = 3, node = 1
Output: 4
In the above example if 1 is given as the node, then the DFS of subtree will be
1 2 4 6 7 5 3, hence if M is 3, then the 3rd node is 4
Input: M = 4, node = 2
Output: 7
If 2 is given as the node, then the DFS of the subtree will be 2 4 6 7 5., hence
if M is 4 then the 4th node is 7.
Approach:
2109
Chapter 358. Queries for M-th node in the DFS of subtree
2110
Chapter 358. Queries for M-th node in the DFS of subtree
{
// index of node in the original DFS
int ind = mp[node];
// height of subtree of node
return a[ind + m - 1];
}
// Function to add edges to a tree
void addEdge(int x, int y)
{
v[x].push_back(y);
v[y].push_back(x);
}
// Marks the index of node in original DFS
void markIndexDfs()
{
int size = a.size();
// marks the index
for (int i = 0; i < size; i++) {
mp[a[i]] = i;
}
}
// Driver Code
int main()
{
int n = 7;
// add edges of a tree
addEdge(1, 2);
addEdge(1, 3);
addEdge(2, 4);
addEdge(2, 5);
addEdge(4, 6);
addEdge(4, 7);
// array to store the height of subtree
// of every node in a tree
int under[n + 1];
// Call the function DFS to generate the DFS
dfs(under, 1, 0);
// Function call to mark the index of node
markIndexDfs();
2111
Chapter 358. Queries for M-th node in the DFS of subtree
int m = 3;
// Query 1
cout << printnodeDFSofSubtree(1, under, m) << endl;
// Query 2
m = 4;
cout << printnodeDFSofSubtree(2, under, m);
return 0;
}
Source
https://www.geeksforgeeks.org/queries-for-m-th-node-in-the-dfs-of-subtree/
2112
Chapter 359
2113
Chapter 359. Queries to find distance between two nodes of a Binary tree
A sparse table will preprocess the minimum values given for an array in Nlogn space i.e.
each node will contain chain of values of log(i) length where i is the index of the ith node in
L array. Each entry in the sparse table says M[i][j] will represent the index of the minimum
value in the subarray starting at i having length 2^j.
The distance between two nodes can be obtained in terms of lowest common ancestor.
This problem can be breakdown into finding levels of each node, finding the Euler
tour of binary tree and building sparse table for LCA, these steps are explained below :
2. Find the LCA of two nodes in the binary tree in O(logn) by Storing Euler tour of
tree in array and computing two other arrays with the help of levels of each node and
Euler tour.
These steps are shown below:
(I) First, find Euler Tour of binary tree.
2114
Chapter 359. Queries to find distance between two nodes of a Binary tree
(III) Then, store First occurrences of all nodes of binary tree in Euler array.
3. Then build sparse table on L array and find the minimum value say X in range (H[A]
to H[B]). Then use the index of value X as an index to Euler array to get LCA, i.e.
Euler[index(X)].
Let, A=8 and B=5.
(I) H[8]= 1 and H[5]=2
(II) we get min value in L array between 1 and 2 as X=0, index=7
(III) Then, LCA= Euler[7], i.e LCA=1.
4. Finally, apply distance formula discussed above to get the distance between two nodes.
Source
https://www.geeksforgeeks.org/queries-find-distance-two-nodes-binary-tree/
2115
Chapter 360
Queries to find distance between two nodes of a Binary tree - O(logn) method - Geeks-
forGeeks
Given a binary tree, the task is to find the distance between two keys in a binary tree, no
parent pointers are given. Distance between two nodes is the minimum number of edges to
be traversed to reach one node from other.
This problem has been already discussed in previous post but it uses three traversals of
the Binary tree, one for finding Lowest Common Ancestor(LCA) of two nodes(let A and B)
and then two traversals for finding distance between LCA and A and LCA and B which has
O(n) time complexity. In this post, a method will be discussed that requires the O(log(n))
time to find LCA of two nodes.
2116
Chapter 360. Queries to find distance between two nodes of a Binary tree – O(logn)
method
The distance between two nodes can be obtained in terms of lowest common ancestor. Fol-
lowing is the formula.
2117
Chapter 360. Queries to find distance between two nodes of a Binary tree – O(logn)
method
2. Find the LCA of two nodes in binary tree in O(logn) by Storing Euler tour
of Binary tree in array and computing two other arrays with the help of
levels of each node and Euler tour.
These steps are shown below:
(I) First, find Euler Tour of binary tree.
(III) Then, store First occurrences of all nodes of binary tree in Euler array.
H stores the indices of nodes from Euler array, so that range of query for
finding minimum can be minimized and their by further optimizing the
query time.
3. Then build segment tree on L array and take the low and high values
from H array that will give us the first occurrences of say Two nodes(A
and B) . Then, <strong>we query segment tree to find the minimum value
say X in range (H[A] to H[B]). Then we use the index of value X as
index to Euler array to get LCA, i.e. Euler[index(X)].
Let, A = 8 and B = 5.
(I) H[8] = 1 and H[5] =2
(II) Querying on Segment tree, we get min value in L array between 1 and
2 as X=0, index=7
(III) Then, LCA= Euler[7], i.e LCA = 1.
2118
Chapter 360. Queries to find distance between two nodes of a Binary tree – O(logn)
method
2119
Chapter 360. Queries to find distance between two nodes of a Binary tree – O(logn)
method
level[p.first->data] = p.second;
// If left child exits, put it in queue
// with current_level +1
if (p.first->left)
q.push({ p.first->left, p.second + 1 });
// If right child exists, put it in queue
// with current_level +1
if (p.first->right)
q.push({ p.first->right, p.second + 1 });
}
}
// Stores Euler Tour
int Euler[MAX];
// index in Euler array
int idx = 0;
// Find Euler Tour
void eulerTree(struct Node* root)
{
// store current node's data
Euler[++idx] = root->data;
// If left node exists
if (root->left) {
// traverse left subtree
eulerTree(root->left);
// store parent node's data
Euler[++idx] = root->data;
}
// If right node exists
if (root->right) {
// traverse right subtree
eulerTree(root->right);
// store parent node's data
Euler[++idx] = root->data;
}
}
// checks for visited nodes
2120
Chapter 360. Queries to find distance between two nodes of a Binary tree – O(logn)
method
int vis[MAX];
// Stores level of Euler Tour
int L[MAX];
// Stores indices of first occurrence
// of nodes in Euler tour
int H[MAX];
// Preprocessing Euler Tour for finding LCA
void preprocessEuler(int size)
{
for (int i = 1; i <= size; i++) {
L[i] = level[Euler[i]];
// If node is not visited before
if (vis[Euler[i]] == 0) {
// Add to first occurrence
H[Euler[i]] = i;
// Mark it visited
vis[Euler[i]] = 1;
}
}
}
// Stores values and positions
pair<int, int> seg[4 * MAX];
// Utility function to find minimum of
// pair type values
pair<int, int> min(pair<int, int> a,
pair<int, int> b)
{
if (a.first <= b.first)
return a;
else
return b;
}
// Utility function to build segment tree
pair<int, int> buildSegTree(int low, int high, int pos)
{
if (low == high) {
seg[pos].first = L[low];
seg[pos].second = low;
return seg[pos];
}
2121
Chapter 360. Queries to find distance between two nodes of a Binary tree – O(logn)
method
2122
Chapter 360. Queries to find distance between two nodes of a Binary tree – O(logn)
method
}
void preProcessing(Node* root, int N)
{
// Build Tree
eulerTree(root);
// Store Levels
FindLevels(root);
// Find L and H array
preprocessEuler(2 * N - 1);
// Build segment Tree
buildSegTree(1, 2 * N - 1, 1);
}
/* Driver function to test above functions */
int main()
{
int N = 8; // Number of nodes
/* Constructing tree given in the above figure */
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
// Function to do all preprocessing
preProcessing(root, N);
cout << "Dist(4, 5) = " << findDistance(4, 5, 2 * N - 1) << "\n";
cout << "Dist(4, 6) = " << findDistance(4, 6, 2 * N - 1) << "\n";
cout << "Dist(3, 4) = " << findDistance(3, 4, 2 * N - 1) << "\n";
cout << "Dist(2, 4) = " << findDistance(2, 4, 2 * N - 1) << "\n";
cout << "Dist(8, 5) = " << findDistance(8, 5, 2 * N - 1) << "\n";
return 0;
}
Output:
Dist(4, 5) = 2
2123
Chapter 360. Queries to find distance between two nodes of a Binary tree – O(logn)
method
Dist(4, 6) = 4
Dist(3, 4) = 3
Dist(2, 4) = 1
Dist(8, 5) = 5
Source
https://www.geeksforgeeks.org/queries-find-distance-two-nodes-binary-tree-ologn-method/
2124
Chapter 361
u = 1 v = 6
we can see from above tree that node
1 is ancestor of node 6 so the answer
will be yes.
u = 1 v = 7
we can see from above tree that node 1
is not an ancestor of node 7 so the
answer will be no.
We can solve this problem using depth first search of the tree. While doing dfs we can
observe a relation between the order in which we visit a node and its ancestors. If we assign
in-time and out-time to each node when entering and leaving that node in dfs then we can
see that for each pair of ancestor-descendant the in-time of ancestor is less than that of
descendant and out-time of ancestor is more than that of descendant, so using this relation
we can find the result for each pair of node in O(1) time.
So time complexity for preprocessing will be O(N) and for the query it will be O(1).
2125
Chapter 361. Query for ancestor-descendant relationship in a tree
#include <bits/stdc++.h>
using namespace std;
// Utility dfs method to assign in and out time
// to each node
void dfs(vector<int> g[], int u, int parent,
int timeIn[], int timeOut[], int& cnt)
{
// assign In-time to node u
timeIn[u] = cnt++;
// call dfs over all neighbors except parent
for (int i = 0; i < g[u].size(); i++) {
int v = g[u][i];
if (v != parent)
dfs(g, v, u, timeIn, timeOut, cnt);
}
// assign Out-time to node u
timeOut[u] = cnt++;
}
// method to preprocess all nodes for assigning time
void preProcess(int edges[][2], int V, int timeIn[],
int timeOut[])
{
vector<int> g[V];
// construct array of vector data structure
// for tree
for (int i = 0; i < V - 1; i++) {
int u = edges[i][0];
int v = edges[i][1];
g[u].push_back(v);
g[v].push_back(u);
}
int cnt = 0;
// call dfs method from root
dfs(g, 0, -1, timeIn, timeOut, cnt);
}
// method returns "yes" if u is a ancestor
// node of v
string isAncestor(int u, int v, int timeIn[],
int timeOut[])
2126
Chapter 361. Query for ancestor-descendant relationship in a tree
{
bool b = (timeIn[u] <= timeIn[v] &&
timeOut[v] <= timeOut[u]);
return (b ? "yes" : "no");
}
// Driver code to test abovea methods
int main()
{
int edges[][2] = {
{ 0, 1 },
{ 0, 2 },
{ 1, 3 },
{ 1, 4 },
{ 2, 5 },
{ 4, 6 },
{ 5, 7 }
};
int E = sizeof(edges) / sizeof(edges[0]);
int V = E + 1;
int timeIn[V], timeOut[V];
preProcess(edges, V, timeIn, timeOut);
int u = 1;
int v = 6;
cout << isAncestor(u, v, timeIn, timeOut) << endl;
u = 1;
v = 7;
cout << isAncestor(u, v, timeIn, timeOut) << endl;
return 0;
}
Output:
yes
no
Source
https://www.geeksforgeeks.org/query-ancestor-descendant-relationship-tree/
2127
Chapter 362
Mathematically,
LCM(l, r) = LCM(arr[l], arr[l+1] , ......... ,
arr[r-1], arr[r])
Examples:
A naive solution would be to traverse the array for every query and calculate the answer by
using,
LCM(a, b) = (a*b) / GCD(a,b)
However as the number of queries can be large, this solution would be impractical.
An efficient solution would be to use segment tree. Recall that in this case, where no update
is required, we can build the tree once and can use that repeatedly to answer the queries.
Each node in the tree should store the LCM value for that particular segment and we can
2128
Chapter 362. Range LCM Queries
use the same formula as above to combine the segments. Hence we can answer each query
efficiently!
Below is a C++ solution for the same.
2129
Chapter 362. Range LCM Queries
2130
Chapter 362. Range LCM Queries
build(1, 0, 10);
// Now we can answer each query efficiently
// Print LCM of (2, 5)
cout << query(1, 0, 10, 2, 5) << endl;
// Print LCM of (5, 10)
cout << query(1, 0, 10, 5, 10) << endl;
// Print LCM of (0, 10)
cout << query(1, 0, 10, 0, 10) << endl;
return 0;
}
Output:
60
15708
78540
Source
https://www.geeksforgeeks.org/range-lcm-queries/
2131
Chapter 363
1. Update : Given indices of a range [L, R]. Paint all the pieces with their respective
opposite color between L and R (i.e. white pieces should be painted with black color
and black pieces should be painted with white color).
2. Get : Given indices of a range [L, R]. Find out the number of black pieces between L
and R.
Let us represent ‘white’ pieces with ‘0’ and ‘black’ pieces with ‘1’.
Prerequisites: Segment Trees | Lazy Propagation
Examples :
Input : N = 4, Q = 5
Get : L = 0, R = 3
Update : L = 1, R = 2
Get : L = 0, R = 1
Update : L = 0, R = 3
Get : L = 0, R = 3
Output : 0
1
2
Explanation :
Query1 : A[] = { 0, 0, 0, 0 } Since initially all pieces are white, number of black pieces will
2132
Chapter 363. Range and Update Query for Chessboard Pieces
be zero.
Query2 : A[] = { 0, 1, 1, 0 }
Query3 : Number of black pieces in [0, 1] = 1
Query4 : Change the color to its opposite color in [0, 3], A[] = { 1, 0, 0, 1 }
Query5 : Number of black pieces in [0, 3] = 2
Naive Approach :
Update(L, R) : Iterate over the subarray from L to R and change the color of all the
pieces (i.e. change 0 to 1 and 1 to 0)
Get(L, R) : To get the number of black pieces, simply count the number of ones in range
[L, R].
Both update and getBlackPieces() function will have O(N) time complexity. The time
complexity in worst case is O(Q * N) where Q is number of queries and N is number of
chessboard pieces.
Efficient Approach :
An efficient method to solve this problem is by using Segment Trees which can reduce the
time complexity of update and getBlackPieces functions to O(LogN).
Build Structure: Each leaf node of segment tree will contain either 0 or 1 depending upon
the color of the piece (i.e. if the piece is black, node will contain 1 otherwise 0). Internal
nodes will contain the sum of ones or number of black pieces of its left child and right child.
Thus, the root node will give us the total number of black pieces in the whole array [0..N-1]
Update Structure : Point updates takes O(Log(N)) time but when there are range
updates, optimize the updates using Lazy Propagation. Below is the modified update
method.
UpdateRange(ss, se)
1. If current node's range lies completely in update query range.
...a) Value of current node becomes the difference of total count
of black pieces in the subtree of current node and current
value of node, i.e. tree[curNode] = (se - ss + 1) - tree[curNode]
...b) Provide the lazy value to its children by setting
lazy[2*curNode] = 1 - lazy[2*curNode]
lazy[2*curNode + 1] = 1 - lazy[2*curNode + 1]
Query Structure : Query Structure will also change a bit in the same way as update
structure by checking pending updates and updating them to get the correct query output.
Below is the implementation of above approach in C++.
2133
Chapter 363. Range and Update Query for Chessboard Pieces
2134
Chapter 363. Range and Update Query for Chessboard Pieces
2135
Chapter 363. Range and Update Query for Chessboard Pieces
2136
Chapter 363. Range and Update Query for Chessboard Pieces
2137
Chapter 363. Range and Update Query for Chessboard Pieces
2138
Chapter 363. Range and Update Query for Chessboard Pieces
/* Function to construct lazy array for
segment tree. This function allocates
memory for lazy array */
int* constructLazy(int arr[], int n)
{
// Allocate memory for lazy array
// Height of lazy array
int x = (int)(ceil(log2(n)));
// Maximum size of lazy array
int max_size = 2 * (int)pow(2, x) - 1;
// Allocate memory
int* lazy = new int[max_size];
// Return the lazy array
return lazy;
}
// Driver program to test above functions
int main()
{
// Intialize the array to zero
// since all pieces are white
int arr[] = { 0, 0, 0, 0 };
int n = sizeof(arr) / sizeof(arr[0]);
// Build segment tree from given array
int* tree = constructST(arr, n);
// Allocate memory for Lazy array
int* lazy = constructLazy(arr, n);
// Print number of black pieces
// from index 0 to 3
cout << "Black Pieces in given range = "
<< getSum(tree, lazy, n, 0, 3) << endl;
// UpdateRange: Change color of pieces
// from index 1 to 2
updateRange(tree, lazy, n, 1, 2);
// Print number of black pieces
// from index 0 to 1
cout << "Black Pieces in given range = "
<< getSum(tree, lazy, n, 0, 1) << endl;
2139
Chapter 363. Range and Update Query for Chessboard Pieces
// UpdateRange: Change color of
// pieces from index 0 to 3
updateRange(tree, lazy, n, 0, 3);
// Print number of black pieces
// from index 0 to 3
cout << "Black Pieces in given range = "
<< getSum(tree, lazy, n, 0, 3) << endl;
return 0;
}
Output:
Time Complexity : Each query and each update will take O(Log(N)) time, where N is
the number of chessboard pieces. Hence for Q queries, worst case complexity will be (Q *
Log(N))
Source
https://www.geeksforgeeks.org/range-update-query-chessboard-pieces/
2140
Chapter 364
Explanation : In the first query, task is to print the largest sum of a contiguous subarray
in range 5-8, which consists of {-2, 1, 5, -3}. The largest sum is 6, which is formed by the
subarray {1, 5}. In the second query, an update operation is done, which updates a[1] to
10, hence the sequence is {10, -3, 4, -1, -2, 1, 5, -3}. In the third query, task is to print the
largest sum of a contiguous subarray in range 1-3, which consists of {10, -3, 4}. The largest
sum is 11, which is formed by the subarray {10, -3, 4}.
A naive approach is to use Kadane’s algorithm for every type-1 query. The complexity of
every type-1 query is O(n). The type-2 query is done in O(1).
Efficient Approach :
An efficient approach is to build a segment tree where each node stores four values(sum,
prefixsum, suffixsum, maxsum), and do a range query on it to find the answer to every
query. The nodes of segment tree store the four values as mentioned above. The parent will
store the merging of left and right child. The parent node stores the value as mentioned
below :
2141
Chapter 364. Range query for Largest Sum Contiguous Subarray
• Parent node’s sum is the summation of left and right child sum.
• Parent node’s prefix sum will be equivalent to maximum of left child’s prefix sum or
left child sum + right child prefix sum.
• Parent node’s suffix sum will be equal to right child suffix sum or right child sum +
suffix sum of left child
• Parent node’s maxsum will be the maxium of prefixsum or suffix sum of parent or the
left or rigth child’s maxsum or the summation of suffixsum of left child and prefixsum
of right child.
2142
Chapter 364. Range query for Largest Sum Contiguous Subarray
#include <bits/stdc++.h>
using namespace std;
// Structure to store
// 4 values that are to be stored
// in the nodes
struct node {
int sum, prefixsum, suffixsum, maxsum;
};
// array to store the segment tree
node tree[4 * 100];
// function to build the tree
void build(int arr[], int low, int high, int index)
{
// the leaf node
if (low == high) {
tree[index].sum = arr[low];
tree[index].prefixsum = arr[low];
tree[index].suffixsum = arr[low];
tree[index].maxsum = arr[low];
}
else {
int mid = (low + high) / 2;
// left subtree
build(arr, low, mid, 2 * index + 1);
// right subtree
build(arr, mid + 1, high, 2 * index + 2);
// parent node's sum is the summation
// of left and rigth child
tree[index].sum = tree[2 * index + 1].sum +
tree[2 * index + 2].sum;
// parent node's prefix sum will be equivalent
// to maximum of left child's prefix sum or left
// child sum + right child prefix sum.
tree[index].prefixsum =
max(tree[2 * index + 1].prefixsum,
tree[2 * index + 1].sum +
tree[2 * index + 2].prefixsum);
// parent node's suffix sum will be equal to right
// child suffix sum or rigth child sum + suffix
// sum of left child
2143
Chapter 364. Range query for Largest Sum Contiguous Subarray
tree[index].suffixsum =
max(tree[2 * index + 2].suffixsum,
tree[2 * index + 2].sum +
tree[2 * index + 1].suffixsum);
// maxum will be the maximum of prefix, suffix of
// parent or maximum of left child or right child
// and summation of left child's suffix and right
// child's prefix.
tree[index].maxsum =
max(tree[index].prefixsum,
max(tree[index].suffixsum,
max(tree[2 * index + 1].maxsum,
max(tree[2 * index + 2].maxsum,
tree[2 * index + 1].suffixsum +
tree[2 * index + 2].prefixsum))));
}
}
// function to update the tree
void update(int arr[], int index, int low, int high,
int idx, int value)
{
// the node to be updated
if (low == high) {
tree[index].sum = value;
tree[index].prefixsum = value;
tree[index].suffixsum = value;
tree[index].maxsum = value;
}
else {
int mid = (low + high) / 2;
// if node to be updated is in left subtree
if (idx <= mid)
update(arr, 2 * index + 1, low, mid, idx, value);
// if node to be updated is in right subtree
else
update(arr, 2 * index + 2, mid + 1,
high, idx, value);
// parent node's sum is the summation of left
// and rigth child
tree[index].sum = tree[2 * index + 1].sum +
tree[2 * index + 2].sum;
2144
Chapter 364. Range query for Largest Sum Contiguous Subarray
2145
Chapter 364. Range query for Largest Sum Contiguous Subarray
2146
Chapter 364. Range query for Largest Sum Contiguous Subarray
int index = 1;
int value = 10;
a[index - 1] = value;
update(a, 0, 0, n - 1, index - 1, value);
// 3rd type-1 query
l = 1, r = 3;
cout << query(a, 0, 0, n - 1, l - 1, r - 1).maxsum;
return 0;
}
Output:
6
11
Time Complexity : O(n log n) for building the tree, O(log n) for every type-1 query, O(1)
for type-2 query.
Improved By : FelipeNoronha
Source
https://www.geeksforgeeks.org/range-query-largest-sum-contiguous-subarray/
2147
Chapter 365
2148
Chapter 365. Relationship between number of nodes and height of binary tree
2149
Chapter 365. Relationship between number of nodes and height of binary tree
If there are n nodes in a binary search tree, maximum height of the binary search tree is n-1
and minimum height is floor(log2n).
Calculating minimum and maximum number of nodes from height –
If binary search tree has height h, minimum number of nodes is n+1 (in case of left
skewed and right skewed binary search tree).
If binary search tree has height h, maximum number of nodes will be when all levels are
completely full. Total number of nodes will be 2^0 + 2^1 + …. 2^h = 2^(h+1)-1.
All the rules in BST are same as in binary tree and can be visualized in the same way.
Que-1. The height of a tree is the length of the longest root-to-leaf path in it. The maximum
and the minimum number of nodes in a binary tree of height 5 are:
(A) 63 and 6, respectively
(B) 64 and 5, respectively
(C) 32 and 6, respectively
(D) 31 and 5, respectively
Solution: According to formula discussed,
max number of nodes = 2^(h+1)-1 = 2^6-1 =63.
min number of nodes = h+1 = 5+1 = 6.
Que-2. Which of the following height is not possible for a binary tree with 50 nodes?
(A) 4
(B) 5
(C) 6
(D) None
Solution: According to formula discussed,
Minimum height with 50 nodes = floor(log250) = 5. Therefore, height 4 is not possible.
Improved By : cssd1983
Source
https://www.geeksforgeeks.org/relationship-number-nodes-height-binary-tree/
2150
Chapter 366
Remove all nodes which don’t lie in any path with sum>= k - GeeksforGeeks
Given a binary tree, a complete path is defined as a path from root to a leaf. The sum of
all nodes on that path is defined as the sum of that path. Given a number K, you have to
remove (prune the tree) all nodes which don’t lie in any path with sum>=k.
Note: A node can be part of multiple paths. So we have to delete it only in case when all
paths from it have sum less than K.
2151
Chapter 366. Remove all nodes which don’t lie in any path with sum>= k
\ / /
9 12 10
/ \ \
13 14 11
/
15
The idea is to traverse the tree and delete nodes in bottom up manner. While traversing the
tree, recursively calculate the sum of nodes from root to leaf node of each path. For each
visited node, checks the total calculated sum against given sum “k”. If sum is less than k,
then free(delete) that node (leaf node) and return the sum back to the previous node. Since
the path is from root to leaf and nodes are deleted in bottom up manner, a node is deleted
only when all of its descendants are deleted. Therefore, when a node is deleted, it must be
a leaf in the current Binary Tree.
Following is the implementation of the above approach.
C++
#include <stdio.h>
#include <stdlib.h>
// A utility function to get maximum of two integers
int max(int l, int r) { return (l > r ? l : r); }
// A Binary Tree Node
struct Node
{
int data;
struct Node *left, *right;
};
// A utility function to create a new Binary Tree node with given data
2152
Chapter 366. Remove all nodes which don’t lie in any path with sum>= k
2153
Chapter 366. Remove all nodes which don’t lie in any path with sum>= k
Java
2154
Chapter 366. Remove all nodes which don’t lie in any path with sum>= k
2155
Chapter 366. Remove all nodes which don’t lie in any path with sum>= k
{
// Base Case
if (root == null) return null;
// Initialize left and right
// sums as sum from root to
// this node (including this node)
INT lsum = new INT(sum.v + (root.data));
INT rsum = new INT(lsum.v);
// Recursively prune left
// and right subtrees
root.left = pruneUtil(root.left, k, lsum);
root.right = pruneUtil(root.right, k, rsum);
// Get the maximum of
// left and right sums
sum.v = max(lsum.v, rsum.v);
// If maximum is smaller
// than k, then this node
// must be deleted
if (sum.v < k)
{
root = null;
}
return root;
}
// A wrapper over pruneUtil()
static Node prune(Node root, int k)
{
INT sum = new INT(0);
return pruneUtil(root, k, sum);
}
// Driver Code
public static void main(String args[])
{
int k = 45;
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
root.right.left = newNode(6);
2156
Chapter 366. Remove all nodes which don’t lie in any path with sum>= k
root.right.right = newNode(7);
root.left.left.left = newNode(8);
root.left.left.right = newNode(9);
root.left.right.left = newNode(12);
root.right.right.left = newNode(10);
root.right.right.left.right = newNode(11);
root.left.left.right.left = newNode(13);
root.left.left.right.right = newNode(14);
root.left.left.right.right.left = newNode(15);
System.out.println("Tree before truncation\n");
print(root);
root = prune(root, k); // k is 45
System.out.println("\n\nTree after truncation\n");
print(root);
}
}
// This code is contributed by Arnab Kundu
Output:
Time Complexity: O(n), the solution does a single traversal of given Binary Tree.
A Simpler Solution:
The above code can be simplified using the fact that nodes are deleted in bottom up manner.
The idea is to keep reducing the sum when traversing down. When we reach a leaf and sum
is greater than the leaf’s data, then we delete the leaf. Note that deleting nodes may convert
a non-leaf node to a leaf node and if the data for the converted leaf node is less than the
current sum, then the converted leaf should also be deleted.
Thanks to vicky for suggesting this solution in below comments.
#include <stdio.h>
#include <stdlib.h>
// A Binary Tree Node
struct Node
2157
Chapter 366. Remove all nodes which don’t lie in any path with sum>= k
{
int data;
struct Node *left, *right;
};
// A utility function to create a new Binary
// Tree node with given data
struct Node* newNode(int data)
{
struct Node* node =
(struct Node*) malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
// print the tree in LVR (Inorder traversal) way.
void print(struct Node *root)
{
if (root != NULL)
{
print(root->left);
printf("%d ",root->data);
print(root->right);
}
}
/* Main function which truncates the binary tree. */
struct Node *prune(struct Node *root, int sum)
{
// Base Case
if (root == NULL) return NULL;
// Recur for left and right subtrees
root->left = prune(root->left, sum - root->data);
root->right = prune(root->right, sum - root->data);
// If we reach leaf whose data is smaller than sum,
// we delete the leaf. An important thing to note
// is a non-leaf node can become leaf when its
// chilren are deleted.
if (root->left==NULL && root->right==NULL)
{
if (root->data < sum)
{
free(root);
return NULL;
}
2158
Chapter 366. Remove all nodes which don’t lie in any path with sum>= k
}
return root;
}
// Driver program to test above function
int main()
{
int k = 45;
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->left->left->right = newNode(9);
root->left->right->left = newNode(12);
root->right->right->left = newNode(10);
root->right->right->left->right = newNode(11);
root->left->left->right->left = newNode(13);
root->left->left->right->right = newNode(14);
root->left->left->right->right->left = newNode(15);
printf("Tree before truncation\n");
print(root);
root = prune(root, k); // k is 45
printf("\n\nTree after truncation\n");
print(root);
return 0;
}
Java
2159
Chapter 366. Remove all nodes which don’t lie in any path with sum>= k
2160
Chapter 366. Remove all nodes which don’t lie in any path with sum>= k
return;
print(root.left);
System.out.print(root.data + " ");
print(root.right);
}
}
// Driver class to test above function
public class GFG {
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
tree.root.left.left.left = new Node(8);
tree.root.left.left.right = new Node(9);
tree.root.left.right.left = new Node(12);
tree.root.right.right.left = new Node(10);
tree.root.right.right.left.right = new Node(11);
tree.root.left.left.right.left = new Node(13);
tree.root.left.left.right.right = new Node(14);
tree.root.left.left.right.right.left = new Node(15);
System.out.println("Tree before truncation");
tree.print(tree.root);
tree.prune(tree.root, 45);
System.out.println("\nTree after truncation");
tree.print(tree.root);
}
}
// This code is contributed by Shweta Singh
Python3
"""
Python program to remove all nodes which don’t
lie in any path with sum>= k
"""
2161
Chapter 366. Remove all nodes which don’t lie in any path with sum>= k
# binary tree node contains data field , left
# and right pointer
class Node:
# constructor to create tree node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to remove all nodes which do not
# lie in th sum path
def prune(root, sum):
# Base case
if root is None:
return None
# Recur for left and right subtree
root.left = prune(root.left, sum - root.data)
root.right = prune(root.right, sum - root.data)
# if node is leaf and sum is found greater
# than data than remove node An important
# thing to remember is that a non-leaf node
# can become a leaf when its children are
# removed
if root.left is None and root.right is None:
if sum > root.data:
return None
return root
# inorder traversal
def inorder(root):
if root is None:
return
inorder(root.left)
print(root.data, "", end="")
inorder(root.right)
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
2162
Chapter 366. Remove all nodes which don’t lie in any path with sum>= k
root.right.left = Node(6)
root.right.right = Node(7)
root.left.left.left = Node(8)
root.left.left.right = Node(9)
root.left.right.left = Node(12)
root.right.right.left = Node(10)
root.right.right.left.right = Node(11)
root.left.left.right.left = Node(13)
root.left.left.right.right = Node(14)
root.left.left.right.right.left = Node(15)
print("Tree before truncation")
inorder(root)
prune(root, 45)
print("\nTree after truncation")
inorder(root)
# This code is contributed by Shweta Singh
Output:
This article is contributed by Chandra Prakash. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Improved By : shweta44, andrew1234
Source
https://www.geeksforgeeks.org/remove-all-nodes-which-lie-on-a-path-having-sum-less-than-k/
2163
Chapter 367
1
/ \
2 3
/ \ \
4 5 6
/ /
7 8
Input: Root of above Binary Tree
k = 4
2164
Chapter 367. Remove nodes on root to leaf paths of length < K
We strongly recommend to minimize your browser and try this yourself first
The idea here is to use post order traversal of the tree. Before removing a node we need to
check that all the children of that node in the shorter path are already removed.
There are 2 cases:
i) This node becomes a leaf node in which case it needs to be deleted.
ii) This node has other child on a path with path length >= k. In that case it needs not to
be deleted.
The implementation of above approach is as below :
C/C++
2165
Chapter 367. Remove nodes on root to leaf paths of length < K
//Base condition
if (root == NULL)
return NULL;
// Traverse the tree in postorder fashion so that if a leaf
// node path length is shorter than k, then that node and
// all of its descendants till the node which are not
// on some other path are removed.
root->left = removeShortPathNodesUtil(root->left, level + 1, k);
root->right = removeShortPathNodesUtil(root->right, level + 1, k);
// If root is a leaf node and it's level is less than k then
// remove this node.
// This goes up and check for the ancestor nodes also for the
// same condition till it finds a node which is a part of other
// path(s) too.
if (root->left == NULL && root->right == NULL && level < k)
{
delete root;
return NULL;
}
// Return root;
return root;
}
// Method which calls the utitlity method to remove the short path
// nodes.
Node *removeShortPathNodes(Node *root, int k)
{
int pathLen = 0;
return removeShortPathNodesUtil(root, 1, k);
}
//Method to print the tree in inorder fashion.
void printInorder(Node *root)
{
if (root)
{
printInorder(root->left);
cout << root->data << " ";
printInorder(root->right);
}
}
// Driver method.
int main()
{
2166
Chapter 367. Remove nodes on root to leaf paths of length < K
int k = 4;
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->left->left = newNode(7);
root->right->right = newNode(6);
root->right->right->left = newNode(8);
cout << "Inorder Traversal of Original tree" << endl;
printInorder(root);
cout << endl;
cout << "Inorder Traversal of Modified tree" << endl;
Node *res = removeShortPathNodes(root, k);
printInorder(res);
return 0;
}
Java
2167
Chapter 367. Remove nodes on root to leaf paths of length < K
2168
Chapter 367. Remove nodes on root to leaf paths of length < K
Output:
Time complexity of the above solution is O(n) where n is number of nodes in given Binary
Tree.
This article is contributed by Kumar Gautam. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/remove-nodes-root-leaf-paths-length-k/
2169
Chapter 368
Replace each node in binary tree with the sum of its inorder predecessor and successor -
GeeksforGeeks
Given a binary tree containing n nodes. The problem is to replace each node in the binary
tree with the sum of its inorder predecessor and inorder successor.
Examples:
Input : 1
/ \
2 3
/ \ / \
4 5 6 7
Output : 11
/ \
9 13
/ \ / \
2 3 4 3
For 1:
Inorder predecessor = 5
Inorder successor = 6
Sum = 11
For 4:
Inorder predecessor = 0
2170
Chapter 368. Replace each node in binary tree with the sum of its inorder predecessor and
successor
For 7:
Inorder predecessor = 3
Inorder successor = 0
(as inorder successor is not present)
Sum = 3
Approach: Create an array arr. Store 0 at index 0. Now, store the inorder traversal of
tree in the array arr. Then, store 0 at last index. 0’s are stored as inorder predecessor of
leftmost leaf and inorder successor of rightmost leaf is not present. Now, perform inorder
traversal and while traversing node replace node’s value with arr[i-1] + arr[i+1] and then
increment i. In the beginning initialize i = 1. For an element arr[i], the values arr[i-1] and
arr[i+1] are its inorder predecessor and inorder successor respectively.
2171
Chapter 368. Replace each node in binary tree with the sum of its inorder predecessor and
successor
{
// if root is NULL
if (!root)
return;
// first recur on left child
storeInorderTraversal(root->left, arr);
// then store the root's data in 'arr'
arr.push_back(root->data);
// now recur on right child
storeInorderTraversal(root->right, arr);
}
// function to replace each node with the sum of its
// inorder predecessor and successor
void replaceNodeWithSum(struct Node* root,
vector<int> arr, int* i)
{
// if root is NULL
if (!root)
return;
// first recur on left child
replaceNodeWithSum(root->left, arr, i);
// replace node's data with the sum of its
// inorder predecessor and successor
root->data = arr[*i - 1] + arr[*i + 1];
// move 'i' to point to the next 'arr' element
++*i;
// now recur on right child
replaceNodeWithSum(root->right, arr, i);
}
// Utility function to replace each node in binary
// tree with the sum of its inorder predecessor
// and successor
void replaceNodeWithSumUtil(struct Node* root)
{
// if tree is empty
if (!root)
return;
vector<int> arr;
2172
Chapter 368. Replace each node in binary tree with the sum of its inorder predecessor and
successor
// store the value of inorder predecessor
// for the leftmost leaf
arr.push_back(0);
// store the inoder traversal of the tree in 'arr'
storeInorderTraversal(root, arr);
// store the value of inorder successor
// for the rightmost leaf
arr.push_back(0);
// replace each node with the required sum
int i = 1;
replaceNodeWithSum(root, arr, &i);
}
// function to print the preorder traversal
// of a binary tree
void preorderTraversal(struct Node* root)
{
// if root is NULL
if (!root)
return;
// first print the data of node
cout << root->data << " ";
// then recur on left subtree
preorderTraversal(root->left);
// now recur on right subtree
preorderTraversal(root->right);
}
// Driver program to test above
int main()
{
// binary tree formation
struct Node* root = getNode(1); /* 1 */
root->left = getNode(2); /* / \ */
root->right = getNode(3); /* 2 3 */
root->left->left = getNode(4); /* / \ / \ */
root->left->right = getNode(5); /* 4 5 6 7 */
root->right->left = getNode(6);
root->right->right = getNode(7);
cout << "Preorder Traversal before tree modification:n";
2173
Chapter 368. Replace each node in binary tree with the sum of its inorder predecessor and
successor
preorderTraversal(root);
replaceNodeWithSumUtil(root);
cout << "\nPreorder Traversal after tree modification:n";
preorderTraversal(root);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/replace-node-binary-tree-sum-inorder-predecessor-successor/
2174
Chapter 369
3 0
/ \ / \
2 5 == >; 1 1
/ \ / \
1 4 2 2
The idea is to traverse tree starting from root. While traversing pass depth of node as
parameter. We can track depth by passing it as 0 for root and one-plus-current-depth for
children.
Below is C++ implementation of the idea.
2175
Chapter 369. Replace node with depth in a binary tree
2176
Chapter 369. Replace node with depth in a binary tree
root->right = newNode(5);
root->left->left = newNode(1);
root->left->right = newNode(4);
cout << "Before Replacing Nodes\n";
printInorder(root);
replaceNode(root);
cout << endl;
cout << "After Replacing Nodes\n";
printInorder(root);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/replace-node-with-depth-in-a-binary-tree/
2177
Chapter 370
Example Tree
Reverse Level order traversal of the above tree is “4 5 2 3 1”.
Both methods for normal level order traversal can be easily modified to do reverse level
order traversal.
METHOD 1 (Recursive function to print a given level)
We can easily modify the method 1 of the normal level order traversal. In method 1, we
have a method printGivenLevel() which prints a given level number. The only thing we
need to change is, instead of calling printGivenLevel() from first level to last level, we call
it from last level to first level.
C
2178
Chapter 370. Reverse Level Order Traversal
/* A binary tree node has data, pointer to left and right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/*Function protoypes*/
void printGivenLevel(struct node* root, int level);
int height(struct node* node);
struct node* newNode(int data);
/* Function to print REVERSE level order traversal a tree*/
void reverseLevelOrder(struct node* root)
{
int h = height(root);
int i;
for (i=h; i>=1; i--) //THE ONLY LINE DIFFERENT FROM NORMAL LEVEL ORDER
printGivenLevel(root, i);
}
/* Print nodes at a given level */
void printGivenLevel(struct node* root, int level)
{
if (root == NULL)
return;
if (level == 1)
printf("%d ", root->data);
else if (level > 1)
{
printGivenLevel(root->left, level-1);
printGivenLevel(root->right, level-1);
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node->left);
2179
Chapter 370. Reverse Level Order Traversal
Java
2180
Chapter 370. Reverse Level Order Traversal
{
data = item;
left = right;
}
}
class BinaryTree
{
Node root;
/* Function to print REVERSE level order traversal a tree*/
void reverseLevelOrder(Node node)
{
int h = height(node);
int i;
for (i = h; i >= 1; i--)
//THE ONLY LINE DIFFERENT FROM NORMAL LEVEL ORDER
{
printGivenLevel(node, i);
}
}
/* Print nodes at a given level */
void printGivenLevel(Node node, int level)
{
if (node == null)
return;
if (level == 1)
System.out.print(node.data + " ");
else if (level > 1)
{
printGivenLevel(node.left, level - 1);
printGivenLevel(node.right, level - 1);
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(Node node)
{
if (node == null)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node.left);
int rheight = height(node.right);
2181
Chapter 370. Reverse Level Order Traversal
/* use the larger one */
if (lheight > rheight)
return (lheight + 1);
else
return (rheight + 1);
}
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
// Let us create trees shown in above diagram
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("Level Order traversal of binary tree is : ");
tree.reverseLevelOrder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal
Python
2182
Chapter 370. Reverse Level Order Traversal
Output:
Time Complexity: The worst case time complexity of this method is O(n^2). For a skewed
tree, printGivenLevel() takes O(n) time where n is the number of nodes in the skewed tree.
2183
Chapter 370. Reverse Level Order Traversal
// A C++ program to print REVERSE level order traversal using stack and queue
// This approach is adopted from following link
// http://tech-queries.blogspot.in/2008/12/level-order-tree-traversal-in-reverse.html
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
/* A binary tree node has data, pointer to left and right children */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Given a binary tree, print its nodes in reverse level order */
void reverseLevelOrder(node* root)
{
stack <node *> S;
queue <node *> Q;
Q.push(root);
// Do something like normal level order traversal order. Following are the
// differences with normal level order traversal
// 1) Instead of printing a node, we push the node to stack
// 2) Right subtree is visited before left subtree
while (Q.empty() == false)
{
/* Dequeue node and make it root */
root = Q.front();
Q.pop();
S.push(root);
/* Enqueue right child */
if (root->right)
2184
Chapter 370. Reverse Level Order Traversal
Java
2185
Chapter 370. Reverse Level Order Traversal
2186
Chapter 370. Reverse Level Order Traversal
Q.add(node.left);
}
// Now pop all items from stack one by one and print them
while (S.empty() == false)
{
node = S.peek();
System.out.print(node.data + " ");
S.pop();
}
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
// Let us create trees shown in above diagram
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.left = new Node(6);
tree.root.right.right = new Node(7);
System.out.println("Level Order traversal of binary tree is :");
tree.reverseLevelOrder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal
Python
2187
Chapter 370. Reverse Level Order Traversal
# Given a binary tree, print its nodes in reverse level order
def reverseLevelOrder(root):
S = []
Q = []
Q.append(root)
# Do something like normal level order traversal order.
# Following are the differences with normal level order
# traversal:
# 1) Instead of printing a node, we push the node to stack
# 2) Right subtree is visited before left subtree
while(len(Q) > 0 ):
# Dequeue node and make it root
root = Q.pop(0)
S.append(root)
# Enqueue right child
if (root.right):
Q.append(root.right)
# Enqueue left child
if (root.left):
Q.append(root.left)
# Now pop all items from stack one by one and print them
while(len(S) > 0):
root = S.pop()
print root.data,
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
print "Level Order traversal of binary tree is"
reverseLevelOrder(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
2188
Chapter 370. Reverse Level Order Traversal
4 5 6 7 2 3 1
Source
https://www.geeksforgeeks.org/reverse-level-order-traversal/
2189
Chapter 371
Prerequisites :
Morris Traversals
Threaded Binary Trees
In a binary tree with n nodes, there are n + 1 NULL pointers which waste memory. So,
2190
Chapter 371. Reverse Morris traversal using Threaded Binary Tree
threaded binary trees makes use of these NULL pointers to save lots of Memory.
So, in Threaded Binary trees these NULL pointers will store some useful information.
1)Storing predecessor information in NULL left pointers only, called as left threaded binary
trees.
2)Storing successor information in NULL right pointers only, called as right threaded binary
trees.
3)Storing predecessor information in NULL left pointers and successor information in NULL
right pointers, called as fully threaded binary trees or simply threaded binary trees.
Morris traversal can be used to do Inorder traversal, reverse Inorder traversal, Pre-order
traversal with constant extra memory consumed O(1).
Reverse Morris Traversal : It is simply the reverse form of Morris Traversal.In reverse
Morris traversal, first create links to the inorder successor of the current node and print the
data using these links, and finally revert the changes to restore original tree, which will give
a reverse inorder traversal.
Algorithm :
2191
Chapter 371. Reverse Morris traversal using Threaded Binary Tree
int data;
Node *left, *right;
};
// helper function to create a new node
Node *newNode(int data){
Node *temp = new Node;
temp->data = data;
temp->right = temp->left = NULL;
return temp;
}
// function for reverse inorder traversal
void MorrisReverseInorder(Node *root)
{
if(!root)
return ;
// Auxiliary node pointers
Node *curr, *successor;
// initialize current as root
curr = root;
while(curr)
{
// case-1, if curr has no right child then
// visit current and move to left child
if(curr -> right == NULL)
{
cout << curr->data << " ";
curr = curr->left;
}
// case-2
else
{
// find the inorder successor of
// current node i.e left most node in
// right subtree or right child itself
successor = curr->right;
// finding left most in right subtree
while(successor->left != NULL &&
successor->left != curr)
2192
Chapter 371. Reverse Morris traversal using Threaded Binary Tree
successor = successor->left;
// if the left of inorder successor is NULL
if(successor->left == NULL)
{
// then connect left link to current node
successor->left = curr;
// move current to right child
curr = curr->right;
}
// otherwise inorder successor's left is
// not NULL and already left is linked
// with current node
else
{
successor->left = NULL;
// visiting the current node
cout << curr->data << " ";
// move current to its left child
curr = curr->left;
}
}
}
}
// Driver code
int main()
{
/* Constructed binary tree is
1
/ \
2 3
/ \ / \
4 5 6 7
*/
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
2193
Chapter 371. Reverse Morris traversal using Threaded Binary Tree
//reverse inorder traversal.
MorrisReverseInorder(root);
return 0;
}
Output:
7 3 6 1 5 2 4
Source
https://www.geeksforgeeks.org/reverse-morris-traversal-using-threaded-binary-tree/
2194
Chapter 372
Given tree:
a
/ \
b c
/ \ / \
d e f g
/ \ / \ / \ / \
h i j k l m n o
Modified tree:
a
/ \
c b
/ \ / \
d e f g
/ \ / \ / \ / \
o n m l k j i h
Method 1 (Simple)
A simple solution is to do following steps.
1) Access nodes level by level.
2) If current level is odd, then store nodes of this level in an array.
3) Reverse the array and store elements back in tree.
2195
Chapter 372. Reverse alternate levels of a perfect binary tree
2196
Chapter 372. Reverse alternate levels of a perfect binary tree
2197
Chapter 372. Reverse alternate levels of a perfect binary tree
{
// Create an auxiliary array to store nodes of alternate levels
char *arr = new char[MAX];
int index = 0;
// First store nodes of alternate levels
storeAlternate(root, arr, &index, 0);
// Reverse the array
reverse(arr, index);
// Update tree by taking elements from array
index = 0;
modifyTree(root, arr, &index, 0);
}
// A utility function to print indorder traversal of a
// binary tree
void printInorder(struct Node *root)
{
if (root == NULL) return;
printInorder(root->left);
cout << root->data << " ";
printInorder(root->right);
}
// Driver Program to test above functions
int main()
{
struct Node *root = newNode('a');
root->left = newNode('b');
root->right = newNode('c');
root->left->left = newNode('d');
root->left->right = newNode('e');
root->right->left = newNode('f');
root->right->right = newNode('g');
root->left->left->left = newNode('h');
root->left->left->right = newNode('i');
root->left->right->left = newNode('j');
root->left->right->right = newNode('k');
root->right->left->left = newNode('l');
root->right->left->right = newNode('m');
root->right->right->left = newNode('n');
root->right->right->right = newNode('o');
cout << "Inorder Traversal of given tree\n";
printInorder(root);
2198
Chapter 372. Reverse alternate levels of a perfect binary tree
reverseAlternate(root);
cout << "\n\nInorder Traversal of modified tree\n";
printInorder(root);
return 0;
}
Java
2199
Chapter 372. Reverse alternate levels of a perfect binary tree
storeAlternate(node.right, arr, index, l + 1);
}
// Function to modify Binary Tree (All odd level nodes are
// updated by taking elements from array in inorder fashion)
void modifyTree(Node node, char arr[], Index index, int l) {
// Base case
if (node == null) {
return;
}
// Update nodes in left subtree
modifyTree(node.left, arr, index, l + 1);
// Update this node only if this is an odd level node
if (l % 2 != 0) {
node.data = arr[index.index];
(index.index)++;
}
// Update nodes in right subtree
modifyTree(node.right, arr, index, l + 1);
}
// A utility function to reverse an array from index
// 0 to n-1
void reverse(char arr[], int n) {
int l = 0, r = n - 1;
while (l < r) {
char temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
l++;
r--;
}
}
void reverseAlternate() {
reverseAlternate(root);
}
// The main function to reverse alternate nodes of a binary tree
void reverseAlternate(Node node) {
// Create an auxiliary array to store nodes of alternate levels
char[] arr = new char[100];
2200
Chapter 372. Reverse alternate levels of a perfect binary tree
// First store nodes of alternate levels
storeAlternate(node, arr, index_obj, 0);
//index_obj.index = 0;
// Reverse the array
reverse(arr, index_obj.index);
// Update tree by taking elements from array
index_obj.index = 0;
modifyTree(node, arr, index_obj, 0);
}
void printInorder() {
printInorder(root);
}
// A utility function to print indorder traversal of a
// binary tree
void printInorder(Node node) {
if (node == null) {
return;
}
printInorder(node.left);
System.out.print(node.data + " ");
printInorder(node.right);
}
// Driver program to test the above functions
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.root = new Node('a');
tree.root.left = new Node('b');
tree.root.right = new Node('c');
tree.root.left.left = new Node('d');
tree.root.left.right = new Node('e');
tree.root.right.left = new Node('f');
tree.root.right.right = new Node('g');
tree.root.left.left.left = new Node('h');
tree.root.left.left.right = new Node('i');
tree.root.left.right.left = new Node('j');
tree.root.left.right.right = new Node('k');
tree.root.right.left.left = new Node('l');
tree.root.right.left.right = new Node('m');
tree.root.right.right.left = new Node('n');
tree.root.right.right.right = new Node('o');
System.out.println("Inorder Traversal of given tree");
2201
Chapter 372. Reverse alternate levels of a perfect binary tree
tree.printInorder();
tree.reverseAlternate();
System.out.println("");
System.out.println("");
System.out.println("Inorder Traversal of modified tree");
tree.printInorder();
}
}
// This code has been contributed by Mayank Jaiswal
Output:
Time complexity of the above solution is O(n) as it does two inorder traversals of binary
tree.
2202
Chapter 372. Reverse alternate levels of a perfect binary tree
swap(root1->key, root2->key);
// Recur for left and right subtrees (Note : left of root1
// is passed and right of root2 in first call and opposite
// in second call.
preorder(root1->left, root2->right, lvl+1);
preorder(root1->right, root2->left, lvl+1);
}
// This function calls preorder() for left and right children
// of root
void reverseAlternate(struct Node *root)
{
preorder(root->left, root->right, 0);
}
// Inorder traversal (used to print initial and
// modified trees)
void printInorder(struct Node *root)
{
if (root == NULL)
return;
printInorder(root->left);
cout << root->key << " ";
printInorder(root->right);
}
// A utility function to create a new node
Node *newNode(int key)
{
Node *temp = new Node;
temp->left = temp->right = NULL;
temp->key = key;
return temp;
}
// Driver program to test above functions
int main()
{
struct Node *root = newNode('a');
root->left = newNode('b');
root->right = newNode('c');
root->left->left = newNode('d');
root->left->right = newNode('e');
root->right->left = newNode('f');
root->right->right = newNode('g');
root->left->left->left = newNode('h');
root->left->left->right = newNode('i');
2203
Chapter 372. Reverse alternate levels of a perfect binary tree
root->left->right->left = newNode('j');
root->left->right->right = newNode('k');
root->right->left->left = newNode('l');
root->right->left->right = newNode('m');
root->right->right->left = newNode('n');
root->right->right->right = newNode('o');
cout << "Inorder Traversal of given tree\n";
printInorder(root);
reverseAlternate(root);
cout << "\n\nInorder Traversal of modified tree\n";
printInorder(root);
return 0;
}
Output :
Source
https://www.geeksforgeeks.org/reverse-alternate-levels-binary-tree/
2204
Chapter 373
Input :
7
/ \
6 5
/ \ / \
4 3 2 1
Data = 4
Output : Inorder of tree
7 6 3 4 2 5 1
Input :
7
/ \
6 5
/ \ / \
4 3 2 1
Data = 2
Output : Inorder of tree
4 6 3 2 7 5 1
2205
Chapter 373. Reverse tree path
2206
Chapter 373. Reverse tree path
the path is
2207
Chapter 373. Reverse tree path
2208
Chapter 373. Reverse tree path
2209
Chapter 373. Reverse tree path
2210
Chapter 373. Reverse tree path
2211
Chapter 373. Reverse tree path
2212
Chapter 373. Reverse tree path
2213
Chapter 373. Reverse tree path
// Reverse Tree Path
reverseTreePath(root, data);
// Traverse inorder
inorder(root);
return 0;
}
Output:
7 6 3 4 2 5 1
Source
https://www.geeksforgeeks.org/reverse-tree-path/
2214
Chapter 374
Input :
10
/ \
2 3
/ \ / \
7 8 12 15
/
14
Output : 10 3 15 14
The output nodes are the rightmost
nodes of their respective levels.
We have already discussed recursive solution for right view. In this post, level order traver-
salbased solution is discussed.
If we observe carefully, we will see that our main task is to print the right most node of
every level. So, we will do a level order traversal on the tree and print the rightmost node
at every level.
Below is the implementation of above approach:
C++
2215
Chapter 374. Right view of Binary Tree using Queue
2216
Chapter 374. Right view of Binary Tree using Queue
Java
2217
Chapter 374. Right view of Binary Tree using Queue
}
// function to print right view of binary tree
private static void printRightView(Node root)
{
if (root == null)
return;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty())
{
// number of nodes at current level
int n = queue.size();
// Traverse all nodes of current level
for (int i = 1; i <= n; i++) {
Node temp = queue.poll();
// Print the right most element at
// the level
if (i == n)
System.out.print(temp.data + " ");
// Add left node to queue
if (temp.left != null)
queue.add(temp.left);
// Add right node to queue
if (temp.right != null)
queue.add(temp.right);
}
}
}
// Driver code
public static void main(String[] args)
{
// construct binary tree as shown in
// above diagram
Node root = new Node(10);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(7);
root.left.right = new Node(8);
root.right.right = new Node(15);
root.right.left = new Node(12);
2218
Chapter 374. Right view of Binary Tree using Queue
Output:
10 3 15 14
Source
https://www.geeksforgeeks.org/right-view-binary-tree-using-queue/
2219
Chapter 375
For example, in the above tree root to leaf paths exist with following sums.
21 –> 10 – 8 – 3
23 –> 10 – 8 – 5
14 –> 10 – 2 – 2
So the returned value should be true only for numbers 21, 23 and 14. For any other number,
returned value should be false.
Algorithm:
Recursively check if left or right child has path sum equal to ( number – value at current
node)
Implementation:
C
2220
Chapter 375. Root to leaf path sum equal to a given number
#include<stdio.h>
#include<stdlib.h>
#define bool int
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/*
Given a tree and a sum, return true if there is a path from the root
down to a leaf, such that adding up all the values along the path
equals the given sum.
Strategy: subtract the node value from the sum when recurring down,
and check to see if the sum is 0 when you run out of tree.
*/
bool hasPathSum(struct node* node, int sum)
{
/* return true if we run out of tree and sum==0 */
if (node == NULL)
{
return (sum == 0);
}
else
{
bool ans = 0;
/* otherwise check both subtrees */
int subSum = sum - node->data;
/* If we reach a leaf node and sum becomes 0 then return true*/
if ( subSum == 0 && node->left == NULL && node->right == NULL )
return 1;
if(node->left)
ans = ans || hasPathSum(node->left, subSum);
if(node->right)
ans = ans || hasPathSum(node->right, subSum);
return ans;
}
}
2221
Chapter 375. Root to leaf path sum equal to a given number
/* UTILITY FUNCTIONS */
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newnode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
int sum = 21;
/* Constructed binary tree is
10
/ \
8 2
/ \ /
3 5 2
*/
struct node *root = newnode(10);
root->left = newnode(8);
root->right = newnode(2);
root->left->left = newnode(3);
root->left->right = newnode(5);
root->right->left = newnode(2);
if(hasPathSum(root, sum))
printf("There is a root-to-leaf path with sum %d", sum);
else
printf("There is no root-to-leaf path with sum %d", sum);
getchar();
return 0;
}
Java
2222
Chapter 375. Root to leaf path sum equal to a given number
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
/*
Given a tree and a sum, return true if there is a path from the root
down to a leaf, such that adding up all the values along the path
equals the given sum.
Strategy: subtract the node value from the sum when recurring down,
and check to see if the sum is 0 when you run out of tree.
*/
boolean haspathSum(Node node, int sum)
{
if (node == null)
return (sum == 0);
else
{
boolean ans = false;
/* otherwise check both subtrees */
int subsum = sum - node.data;
if (subsum == 0 && node.left == null && node.right == null)
return true;
if (node.left != null)
ans = ans || haspathSum(node.left, subsum);
if (node.right != null)
ans = ans || haspathSum(node.right, subsum);
return ans;
}
}
2223
Chapter 375. Root to leaf path sum equal to a given number
Python
2224
Chapter 375. Root to leaf path sum equal to a given number
and check to see if the sum is 0 when you run out of tree.
"""
# s is the sum
def hasPathSum(node, s):
# Return true if we run out of tree and s = 0
if node is None:
return (s == 0)
else:
ans = 0
# Otherwise check both subtrees
subSum = s - node.data
# If we reach a leaf node and sum becomes 0, then
# return True
if(subSum == 0 and node.left == None and node.right == None):
return True
if node.left is not None:
ans = ans or hasPathSum(node.left, subSum)
if node.right is not None:
ans = ans or hasPathSum(node.right, subSum)
return ans
# Driver program to test above functions
s = 21
root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.right = Node(5)
root.left.left = Node(3)
root.right.left = Node(2)
if hasPathSum(root, s):
print "There is a root-to-leaf path with sum %d" %(s)
else:
print "There is no root-to-leaf path with sum %d" %(s)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output :
True
2225
Chapter 375. Root to leaf path sum equal to a given number
Source
https://www.geeksforgeeks.org/root-to-leaf-path-sum-equal-to-a-given-number/
2226
Chapter 376
Input : 1
/ \
2 3
/ \ / \
4 5 6 3
\ \
8 9
Output : 4
The root to leaf path with maximum distinct
nodes is 1-3-6-8.
A simple solution is to explore all root to leaf paths. In every root to leaf path, count
distinct nodes and finally return the maximum count.
An efficient solution is to use hashing. We recursively traverse the tree and maintain
count of distinct nodes on path from root to current node. We recur for left and right
subtrees and finally return maximum of two values.
Below c++ implementation of above idea
2227
Chapter 376. Root to leaf path with maximum distinct nodes
2228
Chapter 376. Root to leaf path with maximum distinct nodes
// return max length unique value path
return largestUinquePathUtil(node, hash);
}
// Driver program to test above functions
int main()
{
// Create binary tree shown in above figure
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->right->left->right = newNode(8);
root->right->right->right = newNode(9);
cout << largestUinquePath(root) << endl;
return 0;
}
Source
https://www.geeksforgeeks.org/root-leaf-path-maximum-distinct-nodes/
2229
Chapter 377
The idea is to traverse the tree and keep track of path length. Whenever we reach a leaf
node, we increment path length count in a hash map.
Once we have traverse the tree, hash map has counts of distinct path lengths. Finally we
print contents of hash map.
2230
Chapter 377. Root to leaf paths having equal lengths in a Binary Tree
2231
Chapter 377. Root to leaf paths having equal lengths in a Binary Tree
Output:
Source
https://www.geeksforgeeks.org/root-leaf-paths-equal-lengths-binary-tree/
2232
Chapter 378
• Search time is O(Log n) in worst case. Time taken by deletion and insertion is amor-
tized O(Log n)
• The balancing idea is to make sure that nodes are � size balanced. Α size balanced
means sizes of left and right subtrees are at most � * (Size of node). The idea is based
on the fact that if a node is Α weight balanced, then it is also height balanced: height
<= log1/&aplpha; (size) + 1
• Unlike other self-balancing BSTs, ScapeGoat tree doesn’t require extra space per node.
For example, Red Black Tree nodes are required to have color. In below implemen-
tation of ScapeGoat Tree, we only have left, right and parent pointers in Node class.
Use of parent is done for simplicity of implementation and can be avoided.
• Create a new node u and insert x using the BST insert algorithm.
• If the depth of u is greater than log3/2 n where n is number of nodes in tree then we
need to make tree balanced. To make balanced, we use below step to find a scapegoat.
– Walk up from u until we reach a node w with size(w) > (2/3)*size(w.parent).
This node is scapegoat
– Rebuild the subtree rooted at w.parent.
2233
Chapter 378. ScapeGoat Tree | Set 1 (Introduction and Insertion)
60 50
/ / \
40 42 58
\ Rebuild / \ / \
50 ---------> 40 47 55 60
\
55
/ \
47 58
/
42
2234
Chapter 378. ScapeGoat Tree | Set 1 (Introduction and Insertion)
{
if (ptr == NULL)
return i;
i = storeInArray(ptr->left, arr, i);
arr[i++] = ptr;
return storeInArray(ptr->right, arr, i);
}
// Class to represent a ScapeGoat Tree
class SGTree
{
private:
Node *root;
int n; // Number of nodes in Tree
public:
void preorder(Node *);
int size(Node *);
bool insert(float x);
void rebuildTree(Node *u);
SGTree() { root = NULL; n = 0; }
void preorder() { preorder(root); }
// Function to built tree with balanced nodes
Node *buildBalancedFromArray(Node **a, int i, int n);
// Height at which element is to be added
int BSTInsertAndFindDepth(Node *u);
};
// Preorder traversal of the tree
void SGTree::preorder(Node *node)
{
if (node != NULL)
{
cout << node->value << " ";
preorder(node -> left);
preorder(node -> right);
}
}
// To count number of nodes in the tree
int SGTree::size(Node *node)
{
if (node == NULL)
return 0;
return 1 + size(node->left) + size(node->right);
}
2235
Chapter 378. ScapeGoat Tree | Set 1 (Introduction and Insertion)
// To insert new element in the tree
bool SGTree::insert(float x)
{
// Create a new node
Node *node = new Node(x);
// Perform BST insertion and find depth of
// the inserted node.
int h = BSTInsertAndFindDepth(node);
// If tree becomes unbalanced
if (h > log32(n))
{
// Find Scapegoat
Node *p = node->parent;
while (3*size(p) <= 2*size(p->parent))
p = p->parent;
// Rebuild tree rooted under scapegoat
rebuildTree(p->parent);
}
return h >= 0;
}
// Function to rebuilt tree from new node. This
// function basically uses storeInArray() to
// first store inorder traversal of BST rooted
// with u in an array.
// Then it converts array to the most possible
// balanced BST using buildBalancedFromArray()
void SGTree::rebuildTree(Node *u)
{
int n = size(u);
Node *p = u->parent;
Node **a = new Node* [n];
storeInArray(u, a, 0);
if (p == NULL)
{
root = buildBalancedFromArray(a, 0, n);
root->parent = NULL;
}
else if (p->right == u)
{
p->right = buildBalancedFromArray(a, 0, n);
p->right->parent = p;
}
2236
Chapter 378. ScapeGoat Tree | Set 1 (Introduction and Insertion)
else
{
p->left = buildBalancedFromArray(a, 0, n);
p->left->parent = p;
}
}
// Function to built tree with balanced nodes
Node * SGTree::buildBalancedFromArray(Node **a,
int i, int n)
{
if (n== 0)
return NULL;
int m = n / 2;
// Now a[m] becomes the root of the new
// subtree a[0],.....,a[m-1]
a[i+m]->left = buildBalancedFromArray(a, i, m);
// elements a[0],...a[m-1] gets stored
// in the left subtree
if (a[i+m]->left != NULL)
a[i+m]->left->parent = a[i+m];
// elements a[m+1],....a[n-1] gets stored
// in the right subtree
a[i+m]->right =
buildBalancedFromArray(a, i+m+1, n-m-1);
if (a[i+m]->right != NULL)
a[i+m]->right->parent = a[i+m];
return a[i+m];
}
// Performs standard BST insert and returns
// depth of the inserted node.
int SGTree::BSTInsertAndFindDepth(Node *u)
{
// If tree is empty
Node *w = root;
if (w == NULL)
{
root = u;
n++;
return 0;
}
// While the node is not inserted
2237
Chapter 378. ScapeGoat Tree | Set 1 (Introduction and Insertion)
2238
Chapter 378. ScapeGoat Tree | Set 1 (Introduction and Insertion)
sgt.insert(4);
sgt.insert(5);
sgt.insert(2);
sgt.insert(3.5);
printf("Preorder traversal of the"
" constructed ScapeGoat tree is \n");
sgt.preorder();
return 0;
}
Output:
7
/ \
6 8
/ \
5 9
/
2
/ \
1 4
/ /
0 3
2239
Chapter 378. ScapeGoat Tree | Set 1 (Introduction and Insertion)
Since, d > log3/2 n i.e., 6 > log3/2 n, so we have to find the scapegoat in order to solve the
problem of exceeding height.
• Now we find a ScapeGoat. We start with newly added node 3.5 and check whether
size(3.5)/size(3) >2/3.
• Since, size(3.5) = 1 and size(3) = 2, so size(3.5)/size(3) = ½ which is less than 2/3.
So, this is not the scapegoat and we move up .
2240
Chapter 378. ScapeGoat Tree | Set 1 (Introduction and Insertion)
• Since 3 is not the scapegoat, we move and check the same condition for node 4. Since
size(3) = 2 and size(4) = 3, so size(3)/size(4) = 2/3 which is not greater than 2/3. So,
this is not the scapegoat and we move up .
2241
Chapter 378. ScapeGoat Tree | Set 1 (Introduction and Insertion)
• Since 3 is not the scapegoat, we move and check the same condition for node 4. Since,
size(3) = 2 and size(4) = 3, so size(3)/size(4) = 2/3 which is not greater than 2/3. So,
this is not the scapegoat and we move up .
• Now, size(4)/size(2) = 3/6. Since, size(4)= 3 and size(2) = 6 but 3/6 is still less than
2/3, which does not fulfill the condition of scapegoat so we again move up.
2242
Chapter 378. ScapeGoat Tree | Set 1 (Introduction and Insertion)
• Now, size(2)/size(5) = 6/7. Since, size(2) = 6 and size(5) = 7. 6/7 >2/3 which fulfills
the condition of scapegoat, so we stop here and hence node 5 is a scapegoat
2243
Chapter 378. ScapeGoat Tree | Set 1 (Introduction and Insertion)
Finally, after finding the scapegoat, rebuilding will be taken at the subtree rooted at scape-
goat i.e., at 5.
Final tree:
• https://en.wikipedia.org/wiki/Scapegoat_tree
• http://opendatastructures.org/ods-java/8_Scapegoat_Trees.html
Source
https://www.geeksforgeeks.org/scapegoat-tree-set-1-introduction-insertion/
2244
Chapter 379
2245
Chapter 379. Second Largest element in n-ary tree
2246
Chapter 379. Second Largest element in n-ary tree
}
// If root is less than first but greater than
// second
else if (!(*second) || root->key > (*second)->key)
*second = root;
// number of children of root
int numChildren = root->child.size();
// recursively calling for every child
for (int i = 0; i < numChildren; i++)
secondLargestUtil(root->child[i], first, second);
}
Node* secondLargest(Node* root)
{
// second will store the second highest value
Node* second = NULL;
// first will store the largest value in the tree
Node* first = NULL;
// calling the helper function
secondLargestUtil(root, &first, &second);
// return the second largest element
return second;
}
// Driver program
int main()
{
/* Let us create below tree
* 5
* / | \
* 1 2 3
* / / \ \
* 15 4 5 6
*/
Node* root = newNode(5);
(root->child).push_back(newNode(1));
(root->child).push_back(newNode(2));
(root->child).push_back(newNode(3));
(root->child[0]->child).push_back(newNode(15));
(root->child[1]->child).push_back(newNode(4));
(root->child[1]->child).push_back(newNode(5));
2247
Chapter 379. Second Largest element in n-ary tree
(root->child[2]->child).push_back(newNode(6));
cout << "Second largest element is : ";
cout << secondLargest(root) - key << endl;
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/second-largest-element-n-ary-tree/
2248
Chapter 380
2249
Chapter 380. Segment Tree | Set 1 (Sum of given range)
int getSum(node, l, r)
{
if the range of the node is within l and r
return value in the node
else if the range of the node is completely outside l and r
return 0
else
return getSum(node's left child, l, r) +
getSum(node's right child, l, r)
}
2250
Chapter 380. Segment Tree | Set 1 (Sum of given range)
Update a value
Like tree construction and query operations, the update can also be done recursively. We
are given an index which needs to be updated. Let diff be the value to be added. We start
from root of the segment tree and add diff to all nodes which have given index in their
range. If a node doesn’t have given index in its range, we don’t make any changes to that
node.
Implementation:
Following is the implementation of segment tree. The program implements construction of
segment tree for any given array. It also implements query and update operations.
C
2251
Chapter 380. Segment Tree | Set 1 (Sum of given range)
2252
Chapter 380. Segment Tree | Set 1 (Sum of given range)
2253
Chapter 380. Segment Tree | Set 1 (Sum of given range)
Java
2254
Chapter 380. Segment Tree | Set 1 (Sum of given range)
constructSTUtil(arr, 0, n - 1, 0);
}
// A utility function to get the middle index from corner indexes.
int getMid(int s, int e) {
return s + (e - s) / 2;
}
/* A recursive function to get the sum of values in given range
of the array. The following are parameters for this function.
st --> Pointer to segment tree
si --> Index of current node in the segment tree. Initially
0 is passed as root is always at index 0
ss & se --> Starting and ending indexes of the segment represented
by current node, i.e., st[si]
qs & qe --> Starting and ending indexes of query range */
int getSumUtil(int ss, int se, int qs, int qe, int si)
{
// If segment of this node is a part of given range, then return
// the sum of the segment
if (qs <= ss && qe >= se)
return st[si];
// If segment of this node is outside the given range
if (se < qs || ss > qe)
return 0;
// If a part of this segment overlaps with the given range
int mid = getMid(ss, se);
return getSumUtil(ss, mid, qs, qe, 2 * si + 1) +
getSumUtil(mid + 1, se, qs, qe, 2 * si + 2);
}
/* A recursive function to update the nodes which have the given
index in their range. The following are parameters
st, si, ss and se are same as getSumUtil()
i --> index of the element to be updated. This index is in
input array.
diff --> Value to be added to all nodes which have i in range */
void updateValueUtil(int ss, int se, int i, int diff, int si)
{
// Base Case: If the input index lies outside the range of
// this segment
if (i < ss || i > se)
return;
2255
Chapter 380. Segment Tree | Set 1 (Sum of given range)
// If the input index is in range of this node, then update the
// value of the node and its children
st[si] = st[si] + diff;
if (se != ss) {
int mid = getMid(ss, se);
updateValueUtil(ss, mid, i, diff, 2 * si + 1);
updateValueUtil(mid + 1, se, i, diff, 2 * si + 2);
}
}
// The function to update a value in input array and segment tree.
// It uses updateValueUtil() to update the value in segment tree
void updateValue(int arr[], int n, int i, int new_val)
{
// Check for erroneous input index
if (i < 0 || i > n - 1) {
System.out.println("Invalid Input");
return;
}
// Get the difference between new value and old value
int diff = new_val - arr[i];
// Update the value in array
arr[i] = new_val;
// Update the values of nodes in segment tree
updateValueUtil(0, n - 1, i, diff, 0);
}
// Return sum of elements in range from index qs (quey start) to
// qe (query end). It mainly uses getSumUtil()
int getSum(int n, int qs, int qe)
{
// Check for erroneous input values
if (qs < 0 || qe > n - 1 || qs > qe) {
System.out.println("Invalid Input");
return -1;
}
return getSumUtil(0, n - 1, qs, qe, 0);
}
// A recursive function that constructs Segment Tree for array[ss..se].
// si is index of current node in segment tree st
int constructSTUtil(int arr[], int ss, int se, int si)
{
// If there is one element in array, store it in current node of
// segment tree and return
2256
Chapter 380. Segment Tree | Set 1 (Sum of given range)
Output:
Time Complexity:
Time Complexity for tree construction is O(n). There are total 2n-1 nodes, and value of
every node is calculated only once in tree construction.
Time complexity to query is O(Logn). To query a sum, we process at most four nodes at
every level and number of levels is O(Logn).
2257
Chapter 380. Segment Tree | Set 1 (Sum of given range)
The time complexity of update is also O(Logn). To update a leaf value, we process one node
at every level and number of levels is O(Logn).
Source
https://www.geeksforgeeks.org/segment-tree-set-1-sum-of-given-range/
2258
Chapter 381
2259
Chapter 381. Segment Tree | Set 2 (Range Minimum Query)
2260
Chapter 381. Segment Tree | Set 2 (Range Minimum Query)
Implementation:
C
2261
Chapter 381. Segment Tree | Set 2 (Range Minimum Query)
2262
Chapter 381. Segment Tree | Set 2 (Range Minimum Query)
return st;
}
// Driver program to test above functions
int main()
{
int arr[] = {1, 3, 2, 7, 9, 11};
int n = sizeof(arr)/sizeof(arr[0]);
// Build segment tree from given array
int *st = constructST(arr, n);
int qs = 1; // Starting index of query range
int qe = 5; // Ending index of query range
// Print minimum value in arr[qs..qe]
printf("Minimum of values in range [%d, %d] is = %d\n",
qs, qe, RMQ(st, n, qs, qe));
return 0;
}
Java
2263
Chapter 381. Segment Tree | Set 2 (Range Minimum Query)
2264
Chapter 381. Segment Tree | Set 2 (Range Minimum Query)
return st[si];
}
/* Function to construct segment tree from given array. This function
allocates memory for segment tree and calls constructSTUtil() to
fill the allocated memory */
void constructST(int arr[], int n)
{
// Allocate memory for segment tree
//Height of segment tree
int x = (int) (Math.ceil(Math.log(n) / Math.log(2)));
//Maximum size of segment tree
int max_size = 2 * (int) Math.pow(2, x) - 1;
st = new int[max_size]; // allocate memory
// Fill the allocated memory st
constructSTUtil(arr, 0, n - 1, 0);
}
// Driver program to test above functions
public static void main(String args[])
{
int arr[] = {1, 3, 2, 7, 9, 11};
int n = arr.length;
SegmentTreeRMQ tree = new SegmentTreeRMQ();
// Build segment tree from given array
tree.constructST(arr, n);
int qs = 1; // Starting index of query range
int qe = 5; // Ending index of query range
// Print minimum value in arr[qs..qe]
System.out.println("Minimum of values in range [" + qs + ", "
+ qe + "] is = " + tree.RMQ(n, qs, qe));
}
}
// This code is contributed by Ankur Narain Verma
Output:
Time Complexity:
2265
Chapter 381. Segment Tree | Set 2 (Range Minimum Query)
Time Complexity for tree construction is O(n). There are total 2n-1 nodes, and value of
every node is calculated only once in tree construction.
Time complexity to query is O(Logn). To query a range minimum, we process at most two
nodes at every level and number of levels is O(Logn).
Please refer following links for more solutions to range minimum query problem.
https://www.geeksforgeeks.org/range-minimum-query-for-static-array/
http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=lowestCommonAncestor#
Range_Minimum_Query_(RMQ)
http://wcipeg.com/wiki/Range_minimum_query
Source
https://www.geeksforgeeks.org/segment-tree-set-1-range-minimum-query/
2266
Chapter 382
1. Find the XOR of elements from index l to r where 0 <= l <= r <= n-1
2. Change value of a specified element of the array to a new value x. We need to do arr[i]
= x where 0 <= i <= n-1.
Solution 1
A simple solution is to run a loop from l to r and calculate xor of elements in given range.
To update a value, simply do arr[i] = x. The first operation takes O(n) time and second
operation takes O(1) time. Worst case time complexity is O(n*q) for q queries
which will take huge time for n ~ 10^5 and q ~ 10^5. Hence this solution will exceed time
limit.
Solution 2
Another solution is to store xor in all possible ranges but there are O(n^2) possible ranges
hence with n ~ 10^5 it wil exceed space complexity, hence without considering time com-
plexity, we can state this solution will not work.
Solution 3 (Segment Tree)
Prerequesite : Segment Tree
We build a segment tree of given array such that array elements are at leaves and internal
nodes store XOR of leaves covered under them.
2267
Chapter 382. Segment Tree | Set 3 (XOR of given range)
2268
Chapter 382. Segment Tree | Set 3 (XOR of given range)
2269
Chapter 382. Segment Tree | Set 3 (XOR of given range)
int constructSTUtil(int arr[], int ss, int se, int *st, int si)
{
// If there is one element in array, store it in current node of
// segment tree and return
if (ss == se)
{
st[si] = arr[ss];
return arr[ss];
}
// If there are more than one elements, then recur for left and
// right subtrees and store the xor of values in this node
int mid = getMid(ss, se);
st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) ^
constructSTUtil(arr, mid+1, se, st, si*2+2);
return st[si];
}
/* Function to construct segment tree from given array. This function
allocates memory for segment tree and calls constructSTUtil() to
fill the allocated memory */
int *constructST(int arr[], int n)
{
// Allocate memory for segment tree
//Height of segment tree
int x = (int)(ceil(log2(n)));
//Maximum size of segment tree
int max_size = 2*(int)pow(2, x) - 1;
// Allocate memory
int *st = (int *)malloc(sizeof(int)*max_size);
// Fill the allocated memory st
constructSTUtil(arr, 0, n-1, st, 0);
// Return the constructed segment tree
return st;
}
// Driver program to test above functions
int main()
{
int arr[] = {1, 3, 5, 7, 9, 11};
int n = sizeof(arr)/sizeof(arr[0]);
// Build segment tree from given array
2270
Chapter 382. Segment Tree | Set 3 (XOR of given range)
Output:
Source
https://www.geeksforgeeks.org/segment-tree-set-3-xor-given-range/
2271
Chapter 383
10
/ \
20 30
/ \ / \
40 50 60 70
Examples:
Input : getRandom(root);
Output : A Random Node From Tree : 3
Input : getRandom(root);
Output : A Random Node From Tree : 2
A simple solution is to store Inorder traversal of tree in an array. Let the count of nodes
be n. To get a random node, we generate a random number from 0 to n-1, use this number
as index in array and return the value at index.
An alternate solution is to modify tree structure. We store count of children in every
node. Consider the above tree. We use inorder traversal here also. We generate a number
smaller than or equal count of nodes. We traverse tree and go to the node at that index.
2272
Chapter 383. Select a Random Node from a tree with equal probability
We use counts to quickly reach the desired node. With counts, we reach in O(h) time where
h is height of tree.
10,6
/ \
20,2 30,2
/ \ / \
40,0 50,0 60,0 70,0
The first value is node and second
value is count of children.
We start traversing the tree, on each node we either go to left subtree or right subtree
considering whether the count of children is less than random count or not.
If the random count is less than the count of children then we go left else we go right.
Below is the implementation of above Algorithm. getElements will return count of children
for root, InsertChildrenCount inserts children data to each node, RandomNode return the
random node with the help of Utility Function RandomNodeUtil.
Source
https://www.geeksforgeeks.org/select-random-node-tree-equal-probability/
C++
2273
Chapter 383. Select a Random Node from a tree with equal probability
{
if (!root)
return 0;
return getElements(root->left) +
getElements(root->right) + 1;
}
// Inserts Children count for each node
void insertChildrenCount(Node*& root)
{
if (!root)
return;
root->children = getElements(root) - 1;
insertChildrenCount(root->left);
insertChildrenCount(root->right);
}
// returns number of children for root
int children(Node* root)
{
if (!root)
return 0;
return root->children + 1;
}
// Helper Function to return a random node
int randomNodeUtil(Node* root, int count)
{
if (!root)
return 0;
if (count == children(root->left))
return root->data;
if (count < children(root->left))
return randomNodeUtil(root->left, count);
return randomNodeUtil(root->right,
count - children(root->left) - 1);
}
// Returns Random node
int randomNode(Node* root)
{
srand(time(0));
int count = rand() % (root->children + 1);
2274
Chapter 383. Select a Random Node from a tree with equal probability
Time Complexity of randomNode is O(h) where h is height of tree. Note that we are either
moving to right or to left at a time.
2275
Chapter 384
2276
Chapter 384. Serialize and Deserialize a Binary Tree
Input:
20
/ \
8 22
Output: 20 8 -1 -1 22 -1 -1
Input:
20
/
8
/ \
4 12
/ \
10 14
Output: 20 8 4 -1 -1 12 10 -1 -1 14 -1 -1 -1
Input:
20
2277
Chapter 384. Serialize and Deserialize a Binary Tree
/
8
/
10
/
5
Output: 20 8 10 5 -1 -1 -1 -1 -1
Input:
20
\
8
\
10
\
5
Output: 20 -1 8 -1 10 -1 5 -1 -1
Deserialization can be done by simply reading data from file one by one.
Following is C++ implementation of the above idea.
2278
Chapter 384. Serialize and Deserialize a Binary Tree
2279
Chapter 384. Serialize and Deserialize a Binary Tree
root->left->right->right = newNode(14);
// Let us open a file and serialize the tree into the file
FILE *fp = fopen("tree.txt", "w");
if (fp == NULL)
{
puts("Could not open file");
return 0;
}
serialize(root, fp);
fclose(fp);
// Let us deserialize the storeed tree into root1
Node *root1 = NULL;
fp = fopen("tree.txt", "r");
deSerialize(root1, fp);
printf("Inorder Traversal of the tree constructed from file:\n");
inorder(root1);
return 0;
}
Output:
2280
Chapter 384. Serialize and Deserialize a Binary Tree
Please note that there are always more leaf nodes than internal nodes in a Binary Tree
(Number of leaf nodes is number of internal nodes plus 1, so this optimization makes sense.
How to serialize n-ary tree?
In an n-ary tree, there is no designated left or right child. We can store an ‘end of children’
marker with every node. The following diagram shows serialization where ‘)’ is used as end
of children marker. We will soon be covering implementation for n-ary tree. The diagram
is taken from here.
References:
http://www.cs.usfca.edu/~brooks/S04classes/cs245/lectures/lecture11.pdf
This article is contributed by Shivam Gupta, Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Improved By : sanjanab
Source
https://www.geeksforgeeks.org/serialize-deserialize-binary-tree/
2281
Chapter 385
2282
Chapter 385. Serialize and Deserialize an N-ary Tree
2283
Chapter 385. Serialize and Deserialize an N-ary Tree
2284
Chapter 385. Serialize and Deserialize an N-ary Tree
}
// A utlity function to traverse the constructed N-ary tree
void traverse(Node *root)
{
if (root)
{
printf("%c ", root->key);
for (int i = 0; i < N; i++)
traverse(root->child[i]);
}
}
// Driver program to test above functions
int main()
{
// Let us create an N-ary tree shown in above diagram
Node *root = createDummyTree();
// Let us open a file and serialize the tree into the file
FILE *fp = fopen("tree.txt", "w");
if (fp == NULL)
{
puts("Could not open file");
return 0;
}
serialize(root, fp);
fclose(fp);
// Let us deserialize the storeed tree into root1
Node *root1 = NULL;
fp = fopen("tree.txt", "r");
deSerialize(root1, fp);
printf("Constructed N-Ary Tree from file is \n");
traverse(root1);
return 0;
}
Output:
The above implementation can be optimized in many ways for example by using a vector in
place of array of pointers. We have kept it this way to keep it simple to read and understand.
2285
Chapter 385. Serialize and Deserialize an N-ary Tree
This article is contributed by varun. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/serialize-deserialize-n-ary-tree/
2286
Chapter 386
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ / \ / \ / \
. . . . . . . .
Given two nodes with values x and y. The task is to find the length of the shortest path
between the two nodes.
Examples:
Input: x = 2, y = 3
Output: 2
Input: x = 4, y = 6
Output: 4
2287
Chapter 386. Shortest distance between two nodes in an infinite binary tree
2288
Chapter 386. Shortest distance between two nodes in an infinite binary tree
v2.clear();
while (x) {
v2.push_back(x);
x /= 2;
}
reverse(v2.begin(), v2.end());
}
// function to find distance bewteen two nodes
int Distance()
{
for (int i = v1.size() - 1; i >= 0; i--) {
int x = BinarySearch(v1[i]);
if (x != -1) {
return v1.size() - 1 - i + v2.size() - 1 - x;
}
}
}
// Driver code
int main()
{
int node1 = 2, node2 = 3;
// find ancestors
MakeAncestorNode1(node1);
MakeAncestorNode2(node2);
cout << "Distance between " << node1 <<
" and " << node2 << " is : " << Distance();
return 0;
}
Output:
2289
Chapter 386. Shortest distance between two nodes in an infinite binary tree
Output:
2290
Chapter 386. Shortest distance between two nodes in an infinite binary tree
Source
https://www.geeksforgeeks.org/shortest-distance-between-two-nodes-in-an-infinite-binary-tree/
2291
Chapter 387
Shortest path between two nodes in array like representation of binary tree - GeeksforGeeks
Consider a binary tree in which each node has two children except the leaf nodes. If a node
is labeled as ‘v’ then its right children will be labeled as 2v+1 and left children as 2v. Root
is labelled as
Given two nodes labeled as i and j, the task is to find the shortest distance and the path
from i to j. And print the path of node i and node j from root node.
Examples:
Input : i = 1, j = 2
Output : 1
Path is 1 2
Input : i = 4, j = 3
Output : 3
Path is 4 2 1 3
This problem is mainly an extension of Find distance between two given keys of a Binary
Tree. Here we not only find shortest distance, but also the path.
The between the two nodes i and j will be equal to dist(i, LCA(i, j)) + dist(j, LCA(i,
j)) where LCA means lowest common ancestor of nodes labeled as i and j. If a number
x is represented in binary form then 2*x can be represented by appending 0 to the
binary representation of x and 2x+1 can be represented by appending 1 to the binary
representation of x. This is because when we append 0 all the terms present in binary form
2292
Chapter 387. Shortest path between two nodes in array like representation of binary tree
of x shift left, so it gets doubled similarly when we append 1, we get 2x+1. Suppose the
binary representation of a node is 1010 this tells us the path of this node from root. First
term ‘1’ represents root second term 0 represents left turn then third term 1 represents
right turn from previous node and finally 0 represents left turn.
Node 10 in binary form is 1010 and 13 in binary form is 1101 secondly length of binary
representation of any node also tells about its level in binary tree. Suppose binary represen-
…… .
Thus we know the path of i and j from root .Find out k such that for all p<=k =
.This is the LCA of i and j in binary form .So dist(i, LCA(i, j)) will be m – k and dist(j,
LCA(i, j)) = n – k. so answer will be m + n – 2k. And printing the path is also not a big
issue just store the path of i to LCA and path of j to LCA and concatenate them.
2293
Chapter 387. Shortest path between two nodes in array like representation of binary tree
2294
Chapter 387. Shortest path between two nodes in array like representation of binary tree
Output:
1 2
1
4 2 1 3
3
Time Complexity O( i+ j)
Source
https://www.geeksforgeeks.org/shortest-path-between-two-nodes-in-array-like-representation-of-binary-tree/
2295
Chapter 388
Input :
1
/ \
2 3
Output
2 2
/ \ OR / \
1 3 3 1
Input :
1
/ \
5 8
/ \ / \
2 4 9 10
Output :
2 4
/ \ / \
4 8 OR 2 8 OR .. (any tree with
/ \ / \ / \ / \ same keys and
5 1 9 10 5 1 9 10 no odd is parent
of even)
2296
Chapter 388. Sink Odd nodes in Binary Tree
We strongly recommend you to minimize your browser and try this yourself
first.
Basically, we need to swap odd value of a node with even value of one of its descendants.
The idea is to traverse the tree in postorder fashion. Since we process in postorder, for each
odd node encountered, its left and right subtrees are already balanced (sinked), we check if
it’s an odd node and its left or right child has an even value. If even value is found, we swap
the node’s data with that of even child node and call the procedure on the even child to
balance the subtree. If both children have odd values, that means that all its descendants
are odd.
Below is C++ implementation of the idea.
2297
Chapter 388. Sink Odd nodes in Binary Tree
// if left subtree exists and left child is even
if (root->left && !(root->left->data & 1))
{
// swap root's data with left child and
// fix left subtree
swap(root->data, root->left->data);
sink(root->left);
}
// if right subtree exists and right child is even
else if(root->right && !(root->right->data & 1))
{
// swap root's data with right child and
// fix right subtree
swap(root->data, root->right->data);
sink(root->right);
}
}
// Function to sink all odd nodes to the bottom of binary
// tree. It does a postorder traversal and calls sink()
// if any odd node is found
void sinkOddNodes(Node* &root)
{
// If NULL or is a leaf, do nothing
if (root == NULL || isLeaf(root))
return;
// Process left and right subtrees before this node
sinkOddNodes(root->left);
sinkOddNodes(root->right);
// If root is odd, sink it
if (root->data & 1)
sink(root);
}
// Helper function to do Level Order Traversal of
// Binary Tree level by level. This function is used
// here only for showing modified tree.
void printLevelOrder(Node* root)
{
queue<Node*> q;
q.push(root);
// Do Level order traversal
while (!q.empty())
2298
Chapter 388. Sink Odd nodes in Binary Tree
{
int nodeCount = q.size();
// Print one level at a time
while (nodeCount)
{
Node *node = q.front();
printf("%d ", node->data);
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
nodeCount--;
}
// Line separator for levels
printf("\n");
}
}
// Driver program to test above functions
int main()
{
/* Constructed binary tree is
1
/ \
5 8
/ \ / \
2 4 9 10 */
Node *root = newnode(1);
root->left = newnode(5);
root->right = newnode(8);
root->left->left = newnode(2);
root->left->right = newnode(4);
root->right->left = newnode(9);
root->right->right = newnode(10);
sinkOddNodes(root);
printf("Level order traversal of modified tree\n");
printLevelOrder(root);
return 0;
}
Output :
2299
Chapter 388. Sink Odd nodes in Binary Tree
This article is contributed by Aditya Goel. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/sink-odd-nodes-binary-tree/
2300
Chapter 389
Note: Time complexity analysis of below approaches assume that numbers are fixed size
and finding GCD of two elements take constant time.
Method 1
Find GCD of all subarrays and keep track of the minimum length subarray with gcd k.
Time Complexity of this is O(n3 ), O(n2 ) for each subarray and O(n) for finding gcd of a
subarray.
Method 2
Find GCD of all subarrays using segment tree based approach discussed here. Time com-
plexity of this solution is O(n2 logn), O(n2 ) for each subarray and O(logn) for finding GCD
of subarray using segment tree.
Method 3
The idea is to use Segment Tree and Binary Search to achieve time complexity O(n (logn)2 ).
2301
Chapter 389. Smallest Subarray with given GCD
1. If we have any number equal to ‘k’ in the array then the answer is 1 as GCD of k is
k. Return 1.
2. If there is no number which is divisible by k, then GCD doesn’t exist. Return -1.
3. If none of the above cases is true, the length of minimum subarray is either greater
than 1 or GCD doesn’t exist. In this case, we follow following steps.
• Build segment tree so that we can quicky find GCD of any subarray using the
approach discussed here
• After building Segment Tree, we consider every index as starting point and do
binary search for ending point such that the subarray between these two points
has GCD k
2302
Chapter 389. Smallest Subarray with given GCD
2303
Chapter 389. Smallest Subarray with given GCD
2304
Chapter 389. Smallest Subarray with given GCD
{
// Find middle point and GCD of subarray
// arr[i..mid]
int mid = low + (high-low)/2;
int gcd = findRangeGcd(i, mid, arr, n);
// If GCD is more than k, look further
if (gcd > k)
low = mid;
// If GCD is k, store this point and look for
// a closer point
else if (gcd == k)
{
high = mid;
closest = mid;
break;
}
// If GCD is less than, look closer
else
high = mid;
// If termination condition reached, set
// closest
if (abs(high-low) <= 1)
{
if (findRangeGcd(i, low, arr, n) == k)
closest = low;
else if (findRangeGcd(i, high, arr, n)==k)
closest = high;
break;
}
}
if (closest != 0)
res = min(res, closest - i + 1);
}
// If res was not changed by loop, return -1,
// else return its value.
return (res == n+1) ? -1 : res;
}
// Driver program to test above functions
int main()
{
int n = 8;
2305
Chapter 389. Smallest Subarray with given GCD
int k = 3;
int arr[] = {6, 9, 7, 10, 12, 24, 36, 27};
cout << "Size of smallest sub-array with given"
<< " size is " << findSmallestSubarr(arr, n, k);
return 0;
}
Output:
Example:
First index
Second Index
.
.
.
Sixth Index
2306
Chapter 389. Smallest Subarray with given GCD
Time Complexity: O(n (logn)2 ), O(n) for traversing to each index, O(logn) for each
subarray and O(logn) for GCD of each subarray.
Source
https://www.geeksforgeeks.org/smallest-subarray-with-given-gcd/
2307
Chapter 390
Examples:
Input: N = 20
Output: 21
Explanation: 21 is the smallest element greater than 20.
2308
Chapter 390. Smallest number in BST which is greater than or equal to N
Input: N = 18
Output: 19
Explanation: 19 is the smallest element greater than 18.
Approach:
The idea is to follow the recursive approach for solving the problem i.e. start searching for
the element from the root.
• If there is a leaf node having a value less than N, then element doesn’t exist and return
-1.
• Otherwise, if node’s value is greater than or equal to N and left child is NULL or less
than N then return the node value.
• Else if node’s value is less than N, then search for the element in the right subtree.
• Else search for the element in the left subtree by calling the function recursively ac-
cording to the left or right value.
2309
Chapter 390. Smallest number in BST which is greater than or equal to N
2310
Chapter 390. Smallest number in BST which is greater than or equal to N
Output:
19
Source
https://www.geeksforgeeks.org/smallest-number-in-bst-which-is-greater-than-or-equal-to-n/
2311
Chapter 391
Smallest number in BST which is greater than or equal to N ( Iterative Approach) - Geeks-
forGeeks
Given a Binary Search Tree and a number N, the task is to find the smallest number in the
binary search tree that is greater than or equal to N.
Examples:
Input: N = 5
8
/ \
7 10
/ / \
2 9 13
Output: 7
As 7 is the smallest number in BST which is greater than N = 5.
Input: N = 10
8
/ \
5 11
/ \
2 7
\
3
2312
Chapter 391. Smallest number in BST which is greater than or equal to N ( Iterative
Approach)
Output: 11
As 11 is the smallest number in BST which is greater than N = 10.
A recursive solution for this problem has been already been discussed in this post. Below is
an iterative approach for the problem:
Using Morris Traversal the above problem can be solved in constant space. Find the inorder
successor of the target. Keep two pointers, one pointing to the current node and one for
storing the answer.
Below is the implementation of the above approach:
2313
Chapter 391. Smallest number in BST which is greater than or equal to N ( Iterative
Approach)
// Returns smallest value greater than or
// equal to key.
int findFloor(Node* root, int key)
{
Node *curr = root, *ans = NULL;
// traverse in the tree
while (curr) {
// if the node is smaller than N,
// move right.
if (curr->key > key) {
ans = curr;
curr = curr->left;
}
// if it is equal to N, then it will be
// the answer
else if (curr->key == key) {
ans = curr;
break;
}
else // move to the right of the tree
curr = curr->right;
}
if (ans != NULL)
return ans->key;
return -1;
}
// Driver code
int main()
{
int N = 13;
Node* root = insert(root, 19);
insert(root, 2);
insert(root, 1);
insert(root, 3);
insert(root, 12);
insert(root, 9);
insert(root, 21);
insert(root, 25);
2314
Chapter 391. Smallest number in BST which is greater than or equal to N ( Iterative
Approach)
printf("%d", findFloor(root, 15));
return 0;
}
Output:
19
Source
https://www.geeksforgeeks.org/smallest-number-in-bst-which-is-greater-than-or-equal-to-n-iterative-approach/
2315
Chapter 392
Input :
7
/ \
6 5
/ \ / \
4 3 2 1
Output :
Every level minimum is
level 0 min is = 7
level 1 min is = 5
level 2 min is = 1
Input :
7
/ \
16 1
/ \
4 13
Output :
Every level minimum is
2316
Chapter 392. Smallest value in each level of Binary Tree
level 0 min is = 7
level 1 min is = 1
level 2 min is = 4
2317
Chapter 392. Smallest value in each level of Binary Tree
if (root->data < res[level])
res[level] = root->data;
printPerLevelMinimum(root->right,
res, level + 1);
}
}
void perLevelMinimumUtility(Node* root)
{
// height of tree for the size of
// vector array
int n = heightoftree(root), i;
// vector for store all minimum of
// every level
vector<int> res(n, INT_MAX);
// save every level minimum using
// inorder traversal
printPerLevelMinimum(root, res, 0);
// print every level minimum
cout << "Every level minimum is\n";
for (i = 0; i < n; i++) {
cout << "level " << i <<" min is = "
<< res[i] << "\n";
}
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown
// in above diagram
2318
Chapter 392. Smallest value in each level of Binary Tree
Output:-
2319
Chapter 392. Smallest value in each level of Binary Tree
2320
Chapter 392. Smallest value in each level of Binary Tree
2321
Chapter 392. Smallest value in each level of Binary Tree
{
// Let us create binary tree shown
// in above diagram
Node* root = newNode(7);
root->left = newNode(6);
root->right = newNode(5);
root->left->left = newNode(4);
root->left->right = newNode(3);
root->right->left = newNode(2);
root->right->right = newNode(1);
/* 7
/ \
6 5
/ \ / \
4 3 2 1 */
cout << "Every Level minimum is"
<< "\n";
printPerLevelMinimum(root);
return 0;
}
Output:-
Source
https://www.geeksforgeeks.org/smallest-value-level-binary-tree/
2322
Chapter 393
Algorithm
In the previous post, we discussed construction of BST from sorted Linked List. Construct-
ing from sorted array in O(n) time is simpler as we can get the middle element in O(1) time.
Following is a simple algorithm where we first find the middle node of list and make it root
of the tree to be constructed.
2323
Chapter 393. Sorted Array to Balanced BST
created in step 1.
b) Get the middle of right half and make it right child of the
root created in step 1.
Following is the implementation of the above algorithm. The main code which creates
Balanced BST is highlighted.
C
#include<stdio.h>
#include<stdlib.h>
/* A Binary Tree node */
struct TNode
{
int data;
struct TNode* left;
struct TNode* right;
};
struct TNode* newNode(int data);
/* A function that constructs Balanced Binary Search Tree from a sorted array */
struct TNode* sortedArrayToBST(int arr[], int start, int end)
{
/* Base Case */
if (start > end)
return NULL;
/* Get the middle element and make it root */
int mid = (start + end)/2;
struct TNode *root = newNode(arr[mid]);
/* Recursively construct the left subtree and make it
left child of root */
root->left = sortedArrayToBST(arr, start, mid-1);
/* Recursively construct the right subtree and make it
right child of root */
root->right = sortedArrayToBST(arr, mid+1, end);
return root;
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct TNode* newNode(int data)
{
2324
Chapter 393. Sorted Array to Balanced BST
Java
2325
Chapter 393. Sorted Array to Balanced BST
class BinaryTree {
static Node root;
/* A function that constructs Balanced Binary Search Tree
from a sorted array */
Node sortedArrayToBST(int arr[], int start, int end) {
/* Base Case */
if (start > end) {
return null;
}
/* Get the middle element and make it root */
int mid = (start + end) / 2;
Node node = new Node(arr[mid]);
/* Recursively construct the left subtree and make it
left child of root */
node.left = sortedArrayToBST(arr, start, mid - 1);
/* Recursively construct the right subtree and make it
right child of root */
node.right = sortedArrayToBST(arr, mid + 1, end);
return node;
}
/* A utility function to print preorder traversal of BST */
void preOrder(Node node) {
if (node == null) {
return;
}
System.out.print(node.data + " ");
preOrder(node.left);
preOrder(node.right);
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
int arr[] = new int[]{1, 2, 3, 4, 5, 6, 7};
int n = arr.length;
root = tree.sortedArrayToBST(arr, 0, n - 1);
System.out.println("Preorder traversal of constructed BST");
tree.preOrder(root);
}
}
2326
Chapter 393. Sorted Array to Balanced BST
// This code has been contributed by Mayank Jaiswal
Python
2327
Chapter 393. Sorted Array to Balanced BST
# driver program to test above function
"""
Constructed balanced BST is
4
/ \
2 6
/ \ / \
1 3 5 7
"""
arr = [1, 2, 3, 4, 5, 6, 7]
root = sortedArrayToBST(arr)
print "PreOrder Traversal of constructed BST ",
preOrder(root)
# This code is contributed by Ishita Tripathi
T(n) = 2T(n/2) + C
T(n) --> Time taken for an array of size n
C --> Constant (Finding middle of array and linking root to left
and right subtrees take constant time)
The above recurrence can be solved using Master Theorem as it falls in case 1.
Improved By : IshitaTripathi
Source
https://www.geeksforgeeks.org/sorted-array-to-balanced-bst/
2328
Chapter 394
2329
Chapter 394. Splay Tree | Set 3 (Delete)
2330
Chapter 394. Splay Tree | Set 3 (Delete)
x->left = y->right;
y->right = x;
return y;
}
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
struct node *leftRotate(struct node *x)
{
struct node *y = x->right;
x->right = y->left;
y->left = x;
return y;
}
// This function brings the key at root if key is present in tree.
// If key is not present, then it brings the last accessed item at
// root. This function modifies the tree and returns the new root
struct node *splay(struct node *root, int key)
{
// Base cases: root is NULL or key is present at root
if (root == NULL || root->key == key)
return root;
// Key lies in left subtree
if (root->key > key)
{
// Key is not in tree, we are done
if (root->left == NULL) return root;
// Zig-Zig (Left Left)
if (root->left->key > key)
{
// First recursively bring the key as root of left-left
root->left->left = splay(root->left->left, key);
// Do first rotation for root, second rotation is
// done after else
root = rightRotate(root);
}
else if (root->left->key < key) // Zig-Zag (Left Right)
{
// First recursively bring the key as root of left-right
root->left->right = splay(root->left->right, key);
// Do first rotation for root->left
if (root->left->right != NULL)
root->left = leftRotate(root->left);
2331
Chapter 394. Splay Tree | Set 3 (Delete)
}
// Do second rotation for root
return (root->left == NULL)? root: rightRotate(root);
}
else // Key lies in right subtree
{
// Key is not in tree, we are done
if (root->right == NULL) return root;
// Zag-Zig (Right Left)
if (root->right->key > key)
{
// Bring the key as root of right-left
root->right->left = splay(root->right->left, key);
// Do first rotation for root->right
if (root->right->left != NULL)
root->right = rightRotate(root->right);
}
else if (root->right->key < key)// Zag-Zag (Right Right)
{
// Bring the key as root of right-right and do
// first rotation
root->right->right = splay(root->right->right, key);
root = leftRotate(root);
}
// Do second rotation for root
return (root->right == NULL)? root: leftRotate(root);
}
}
// The delete function for Splay tree. Note that this function
// returns the new root of Splay Tree after removing the key
struct node* delete_key(struct node *root, int key)
{
struct node *temp;
if (!root)
return NULL;
// Splay the given key
root = splay(root, key);
// If key is not present, then
// return root
if (key != root->key)
return root;
2332
Chapter 394. Splay Tree | Set 3 (Delete)
// If key is present
// If left child of root does not exist
// make root->right as root
if (!root->left)
{
temp = root;
root = root->right;
}
// Else if left child exits
else
{
temp = root;
/*Note: Since key == root->key,
so after Splay(key, root->lchild),
the tree we get will have no right child tree
and maximum node in left subtree will get splayed*/
// New root
root = splay(root->left, key);
// Make right child of previous root as
// new root's right child
root->right = temp->right;
}
// free the previous root node, that is,
// the node containing the key
free(temp);
// return root of the new Splay Tree
return root;
}
// A utility function to print preorder traversal of the tree.
// The function also prints height of every node
void preOrder(struct node *root)
{
if (root != NULL)
{
printf("%d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}
2333
Chapter 394. Splay Tree | Set 3 (Delete)
Output:
References:
https://www.geeksforgeeks.org/splay-tree-set-1-insert/
http://courses.cs.washington.edu/courses/cse326/01au/lectures/SplayTrees.ppt
Source
https://www.geeksforgeeks.org/splay-tree-set-3-delete/
2334
Chapter 395
Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in O(sqrt(height)) time) - Geeks-
forGeeks
Prerequisite : Introduction and DFS
The task is to find LCA of two given nodes in a tree (not necessarily a Binary Tree). In
previous posts, we have seen how to calculate LCA using Sparse Matrix DP approach. In
this post, we will see an optimization done on Naive method by sqrt decomposition technique
that works well over the Naive Approach.
Naive Approach
To calculate the LCA of two nodes first of all we will bring both the nodes to same height
by making the node with greater depth jump one parent up the tree till both the nodes
are at same height. Once, both the nodes are at same height we can then start jumping
one parent up for both the nodes simultaneously till both the nodes become equal and that
node will be the LCA of the two originally given nodes.
Consider the below n-ary Tree with depth 9 and lets examine how naive approach works for
this sample tree.
2335
Chapter 395. Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in
O(sqrt(height)) time)
2336
Chapter 395. Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in
O(sqrt(height)) time)
Here in the above Tree we need to calculate the LCA of node 6 and node 30
Clearly node 30 has greater depth than node 6. So first of all we start jumping one parent
above for node 30 till we reach the depth value of node 6 i.e at depth 2.
The orange colored path in the above figure demonstrates the jumping sequence to reach
the depth 2. In this procedure we just simply jump one parent above the current node.
Now both nodes are at same depth 2.Therefore, now both the nodes will jump one parent
up till both the nodes become equal. This end node at which both the nodes become equal
for the first time is our LCA.
The blue color path in the above figure shows the jumping route for both the nodes
C++ code for the above implementation:-
2337
Chapter 395. Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in
O(sqrt(height)) time)
depth[0] = -1;
// precalclating 1)depth. 2)parent.
// for each node
dfs(1,0);
}
// Time Complexity : O(Height of tree)
// recursively jumps one node above
// till both the nodes become equal
int LCANaive(int u,int v)
{
if (u == v) return u;
if (depth[u] > depth[v])
swap(u, v);
v = parent[v];
return LCANaive(u,v);
}
// Driver function to call the above functions
int main(int argc, char const *argv[])
{
// adding edges to the tree
addEdge(1,2);
addEdge(1,3);
addEdge(1,4);
addEdge(2,5);
addEdge(2,6);
addEdge(3,7);
addEdge(4,8);
addEdge(4,9);
addEdge(9,10);
addEdge(9,11);
addEdge(7,12);
addEdge(7,13);
preprocess();
cout << "LCA(11,8) : " << LCANaive(11,8) << endl;
cout << "LCA(3,13) : " << LCANaive(3,13) << endl;
return 0;
}
Output:
LCA(11,8) : 4
2338
Chapter 395. Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in
O(sqrt(height)) time)
LCA(3,13) : 3
Time Complexity : We pre-calculate the depth for each node using one DFS traversal
in O(n). Now in worst case, the two nodes will be two bottom most node on the tree in
different child branches of the root node. Therefore, in this case the root will be the LCA
of both the nodes. Hence, both the nodes will have to jump exactly h height above, where
h is the height of the tree. So, to answer each LCA query Time Complexity will be
O(h).
The Sqrt Decomposition Trick :
We categorize nodes of the tree into different groups according to their depth. Assuming
the depth of the tree h is a perfect square. So once again like the general sqrt decomposition
approach we will be having sqrt(h) blocks or groups. Nodes from depth 0 to depth sqrt(h) –
1 lie in first group; then nodes having depth sqrt(H) to 2*sqrt(h)-1 lie in second group and
so on till last node.
We keep track of the corresponding group number for every node and also depth of every
node. This can be done by one single dfs on the tree (see the code for better understanding).
Sqrt trick :- In naive approach we were jumping one parent up the tree till both nodes
aren’t on the same depth. But here we perform group wise jump. To perform this group
wise jump, we need two parameter associated with each node : 1) parent and 2) jump parent
Here parent for each node is defined as the first node above the current node that is directly
connected to it, where as jump_parent for each node is the node that is the first ancestor
of the current node in the group just above the current node.
So, now we need to maintain 3 parameters for each node :
1) depth
2) parent
3) jump_parent
All these three parameters can be maintained in one dfs(refer to the code for better under-
standing)
Pseudo code for optimization process
LCAsqrt(u, v){
The key concept here is that first we bring both the nodes in same group and having same
jump_parent by climbing decomposed blocks above the tree one by one and then when both
2339
Chapter 395. Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in
O(sqrt(height)) time)
the nodes are in same group and have same jump_parent we use our naive approach to find
LCA of the nodes.
This optimized group jumping technique reduces the iterating space by a factor of sqrt(h)
and hence reduces the Time Complexity(refer below for better time complexity analysis)
Lets decompose the above tree in sqrt(h) groups (h = 9) and calculate LCA for node 6 and
30.
2340
Chapter 395. Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in
O(sqrt(height)) time)
2341
Chapter 395. Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in
O(sqrt(height)) time)
Jump_parent[6] = 0 parent[6] = 3
Jump_parent[5] = 0 parent[5] = 2
Jump_parent[1] = 0 parent[1] = 0
Jump_parent[11] = 6 parent[11] = 6
Jump_parent[15] = 6 parent[15] = 11
Jump_parent[21] = 6 parent[21] = 15
Jump_parent[25] = 21 parent[25] = 21
Jump_parent[26] = 21 parent[26] = 21
Jump_parent[30] = 21 parent[30] = 25
Now at this stage Jump_parent for node 30 is 21 and Jump_parent for node 5 is 0, So we
will climp to jump_parent[30] i.e to node 21
Now once again Jump_parent of node 21 is not equal to Jump_parent of node 5, So once
again we will climb to jump_parent[21] i.e node 6
At this stage jump_parent[6] == jump_parent[5], So now we will use our naive climbing
approach and climb one parent above for both the nodes till it reach node 1 and that will
be the required LCA .
Blue path in the above figure describes jumping path sequence for node 6 and node 5.
The C++ code for the above description is given below:-
2342
Chapter 395. Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in
O(sqrt(height)) time)
int LCANaive(int u,int v)
{
if (u == v) return u;
if (depth[u] > depth[v])
swap(u,v);
v = parent[v];
return LCANaive(u,v);
}
// precalculating the required parameters
// associated with every node
void dfs(int cur, int prev)
{
// marking depth of cur node
depth[cur] = depth[prev] + 1;
// marking parent of cur node
parent[cur] = prev;
// making jump_parent of cur node
if (depth[cur] % block_sz == 0)
/* if it is first node of the block
then its jump_parent is its cur parent */
jump_parent[cur] = parent[cur];
else
/* if it is not the first node of this block
then its jump_parent is jump_parent of
its parent */
jump_parent[cur] = jump_parent[prev];
// propogating the marking down the subtree
for (int i = 0; i<adj[cur].size(); ++i)
if (adj[cur][i] != prev)
dfs(adj[cur][i], cur);
}
// using sqrt decomposition trick
int LCASQRT(int u, int v)
{
while (jump_parent[u] != jump_parent[v])
{
if (depth[u] > depth[v])
2343
Chapter 395. Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in
O(sqrt(height)) time)
// maintaining depth[v] > depth[u]
swap(u,v);
// climb to its jump parent
v = jump_parent[v];
}
// u and v have same jump_parent
return LCANaive(u,v);
}
void preprocess(int height)
{
block_sz = sqrt(height);
depth[0] = -1;
// precalclating 1)depth. 2)parent. 3)jump_parent
// for each node
dfs(1, 0);
}
// Driver function to call the above functions
int main(int argc, char const *argv[])
{
// adding edges to the tree
addEdge(1,2);
addEdge(1,3);
addEdge(1,4);
addEdge(2,5);
addEdge(2,6);
addEdge(3,7);
addEdge(4,8);
addEdge(4,9);
addEdge(9,10);
addEdge(9,11);
addEdge(7,12);
addEdge(7,13);
// here we are directly taking height = 4
// according to the given tree but we can
// pre-calculate height = max depth
// in one more dfs
int height = 4;
preprocess(height);
cout << "LCA(11,8) : " << LCASQRT(11,8) << endl;
cout << "LCA(3,13) : " << LCASQRT(3,13) << endl;
2344
Chapter 395. Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in
O(sqrt(height)) time)
return 0;
}
Output:
LCA(11,8) : 4
LCA(3,13) : 3
Note : The above code works even if height is not perfect square.
Now Lets see how the Time Complexity is changed by this simple grouping technique :
Time Complexity Analysis:
We have divided the tree into sqrt(h) groups according to their depth and each group contain
nodes having max difference in their depth equal to sqrt(h). Now once again take an example
of worst case, let’s say the first node ‘u’ is in first group and the node ‘v’ is in sqrt(h)th
group(last group). So, first we will make group jumps(single group jumps) till we reach
group 1 from last group; This will take exactly sqrt(h) – 1 iterations or jumps. So, till this
step the Time Complexity is O(sqrt(h)).
Now once we are in same group, we call the LCAnaive function. The Time complexity for
LCA_Naive is O(sqrt(h’)), where h’ is the height of the tree. Now, in our case value of h’
will be sqrt(h), because each group has a subtree of at max sqrt(h) height. So the complexity
for this step is also O(sqrt(h)).
Hence, the total Time Complexity will be O(sqrt(h) + sqrt(h)) ~ O(sqrt(h)).
Source
https://www.geeksforgeeks.org/sqrt-square-root-decomposition-set-2-lca-tree-osqrth-time/
2345
Chapter 396
Input :
Edges : 1 2
1 3
2 4
3 5
Colours : 1 1 2 2 1 [1-based indexing where
index denotes the node]
Output : 2
Explanation : The sub-tree {1-2} and {1-2-3-5}
have color difference of 2. Sub-tree {1-2} has two
1-colour nodes and zero 2-colour nodes. So, color
difference is 2. Sub-tree {1-2-3-5} has three 1-colour
nodes and one 2-colour nodes. So color diff = 2.
Method 1 : The problem can be solved by checking every possible sub-tree from every
node of the tree. This will take exponential time as we will check for sub-trees from every
node.
Method 2 : (Efficient) If we observe, we are solving a portion of the tree several times.
This produces recurring sub-problems. We can use Dynamic Programming approach to
get the minimum color difference in one traversal. To make things simpler, we can have
2346
Chapter 396. Sub-tree with minimum color difference in a 2-coloured tree
color values as 1 and -1. Now, if we have a sub-tree with both colored nodes equal, our sum
of colors will be 0. To get the minimum difference, we should have maximum negative sum
or maximum positive sum.
• Case 1 When we need to have a sub-tree with maximum sum : We take a node if its
value > 0, i.e. sum(parent) += max(0, sum(child))
• Case 2 When we need to have a sub-tree with minimum sum(or max negative sum) :
We take a node if its value < 0, i.e. sum(parent) += min(0, sum(child))
To get the minimum sum, we can interchange the colors of nodes, i.e. -1 becomes 1 and
vice-versa.
Below is the C++ implementation :
2347
Chapter 396. Sub-tree with minimum color difference in a 2-coloured tree
2348
Chapter 396. Sub-tree with minimum color difference in a 2-coloured tree
tree[2].push_back(4);
tree[4].push_back(2);
tree[3].push_back(5);
tree[5].push_back(3);
// Index represent the colour of that node
// There is no Node 0, so we start from
// index 1 to N
int colour[] = { 0, 1, 1, -1, -1, 1 };
// Printing the result
cout << maxDiff(tree, colour, N);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/sub-tree-minimum-color-difference-2-coloured-tree/
2349
Chapter 397
2350
Chapter 397. Subtree of all nodes in a tree using DFS
Examples :
Input: N = 5
0 1
1 2
0 3
3 4
Output:
Subtree of node 0 is 1 2 3 4
Subtree of node 1 is 2
Subtree of node 3 is 4
Input: N = 7
0 1
1 2
2 3
0 4
4 5
4 6
Output:
2351
Chapter 397. Subtree of all nodes in a tree using DFS
Subtree of node 0 is 1 2 3 4 5 6
Subtree of node 1 is 2 3
Subtree of node 4 is 5 6
Approach: Do DFS traversal for every node and print all the nodes which are reachable
from a particular node.
Explanation of below code:
2352
Chapter 397. Subtree of all nodes in a tree using DFS
if(!visited[*it])
{
dfs(*it,b);
}
}
endd[a]=b;
}
// Function to print the subtree nodes
void Print(int n)
{
for(int i=0;i<n;i++)
{
// if node is leaf node
// start[i] is equals to endd[i]
if(start[i]!=endd[i])
{
cout<<"subtree of node "<<i<<" is ";
for(int j=start[i]+1;j<=endd[i];j++)
{
cout<<dfs_order[j-1]<<" ";
}
cout<<endl;
}
}
}
// Driver code
int main()
{
// No of nodes n = 10
int n =10, c = 0;
adj[0].push_back(1);
adj[0].push_back(2);
adj[0].push_back(3);
adj[1].push_back(4);
adj[1].push_back(5);
adj[4].push_back(7);
adj[4].push_back(8);
adj[2].push_back(6);
adj[6].push_back(9);
//Calling dfs for node 0
//Considering root node at 0
dfs(0, c);
// Print child nodes
2353
Chapter 397. Subtree of all nodes in a tree using DFS
Print(n);
return 0;
}
Source
https://www.geeksforgeeks.org/sub-tree-nodes-tree-using-dfs/
2354
Chapter 398
Examples :
2355
Chapter 398. Subtree with given sum in a Binary Tree
Output: "Yes"
// sum of all nodes of subtree {3, 5, 9} = 17
Input : sum = 11
Output: "No"
// no subtree with given sum exist
The idea is to traverse tree in Postorder fashion because here we have to think bottom-up
. First calculate the sum of left subtree then right subtree and check if sum_left +
sum_right + cur_node = sum is satisfying the condition that means any subtree with
given sum exist. Below is the recursive implementation of algorithm.
C++
2356
Chapter 398. Subtree with given sum in a Binary Tree
return false;
}
// Here first we go to left sub-tree, then right subtree
// then first we calculate sum of all nodes of subtree
// having ptr as root and assign it as cur_sum
// cur_sum = sum_left + sum_right + ptr->data
// after that we check if cur_sum == sum
int sum_left = 0, sum_right = 0;
return ( sumSubtreeUtil(ptr->left, &sum_left, sum) ||
sumSubtreeUtil(ptr->right, &sum_right, sum) ||
((*cur_sum = sum_left + sum_right + ptr->data) == sum));
}
// Wrapper over sumSubtreeUtil()
bool sumSubtree(struct Node *root, int sum)
{
// Initialize sum of subtree with root
int cur_sum = 0;
return sumSubtreeUtil(root, &cur_sum, sum);
}
// driver program to run the case
int main()
{
struct Node *root = newnode(8);
root->left = newnode(5);
root->right = newnode(4);
root->left->left = newnode(9);
root->left->right = newnode(7);
root->left->right->left = newnode(1);
root->left->right->right = newnode(12);
root->left->right->right->right = newnode(2);
root->right->right = newnode(11);
root->right->right->left = newnode(3);
int sum = 22;
if (sumSubtree(root, sum))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
2357
Chapter 398. Subtree with given sum in a Binary Tree
2358
Chapter 398. Subtree with given sum in a Binary Tree
{
cur_sum = new INT(0);
return false;
}
// Here first we go to left
// sub-tree, then right subtree
// then first we calculate sum
// of all nodes of subtree having
// ptr as root and assign it as
// cur_sum. (cur_sum = sum_left +
// sum_right + ptr.data) after that
// we check if cur_sum == sum
INT sum_left = new INT(0),
sum_right = new INT(0);
return (sumSubtreeUtil(ptr.left, sum_left, sum) ||
sumSubtreeUtil(ptr.right, sum_right, sum) ||
((cur_sum.v = sum_left.v +
sum_right.v + ptr.data) == sum));
}
// Wrapper over sumSubtreeUtil()
static boolean sumSubtree(Node root, int sum)
{
// Initialize sum of
// subtree with root
INT cur_sum = new INT( 0);
return sumSubtreeUtil(root, cur_sum, sum);
}
// Driver Code
public static void main(String args[])
{
Node root = newnode(8);
root.left = newnode(5);
root.right = newnode(4);
root.left.left = newnode(9);
root.left.right = newnode(7);
root.left.right.left = newnode(1);
root.left.right.right = newnode(12);
root.left.right.right.right = newnode(2);
root.right.right = newnode(11);
root.right.right.left = newnode(3);
int sum = 22;
if (sumSubtree(root, sum))
System.out.println( "Yes");
2359
Chapter 398. Subtree with given sum in a Binary Tree
else
System.out.println( "No");
}
}
// This code is contributed
// by Arnab Kundu
Output:
Yes
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/subtree-given-sum-binary-tree/
2360
Chapter 399
Input:
Consider the following tree:
1
/ | \
2 3 4
/ \ \
5 6 7
/ \
8 9
q = 2
n = 1
n = 7
Output:
3
4
Explanation:
In the first query after bursting node 1, there
2361
Chapter 399. Subtrees formed after bursting nodes
Since we are dealing with n-ary tree we can use a representation similar to that of a graph,
and add the bidirectional edges in an array of lists. Now if we burst a node, we can say
for sure that all its children will become separate subtrees. Moreover all the children of its
parents and others ancestors till the root that burst, will also become separate subtrees. So
in our final answer we want to exclude the current node and all its ancestors in the path
till the root. Thus we can form the equation to solve as:
answer[node] = degree[node] + allChild[parent[node]] – countPath[node]
where allChild[]: number of node’s children + number of its
parent’s children + ..+ number of root’s children
parent[]: parent of a node in the tree
degree[]: number of children for a node
countPath[]: number of nodes from root to parent of node
We can fill all the above arrays using depth first search over the adjacency list.We can
start from the root 1, assuming its parent is 0 and recur depth first to propagate its values
to its children. Thus we can pre-process and fill the above arrays initially and return the
equation’s value for each query accordingly.
Following is the C++ implementation of the above approach:
2362
Chapter 399. Subtrees formed after bursting nodes
// go through the adjacent nodes
for (auto it = adj[nod].begin(); it != adj[nod].end(); it++) {
int curr = *it;
// avoid cycling
if (curr == par)
continue;
// recur and go depth first
dfs(curr, nod, adj, allChild, parent, degree, countPath);
}
}
// Driver code
int main()
{
int n = 9;
// adjacency list for each node
list<int> adj[n + 1];
// allChild[]: number of node's children + number of its
// parent's children + ..+ number of root's children
// parent[]: parent of a node in the tree
// degree[]: number of children for a node
// countPath[]: number of nodes from root to parent of node
int allChild[n + 1] = { 0 }, parent[n + 1] = { 0 },
degree[n + 1] = { 0 }, countPath[n + 1] = { 0 };
// construct tree
adj[1].push_back(2);
adj[2].push_back(1);
adj[1].push_back(3);
adj[3].push_back(1);
adj[1].push_back(4);
adj[4].push_back(1);
adj[3].push_back(5);
adj[5].push_back(3);
adj[3].push_back(6);
adj[6].push_back(3);
adj[4].push_back(7);
adj[7].push_back(4);
adj[7].push_back(8);
adj[8].push_back(7);
adj[7].push_back(9);
adj[9].push_back(7);
2363
Chapter 399. Subtrees formed after bursting nodes
Output:
3
4
The time complexity of the above algorithm is O(E * lg(V)) where E id the number of
edges and
V is the number of vertices.
Source
https://www.geeksforgeeks.org/subtrees-formed-bursting-nodes/
2364
Chapter 400
2365
Chapter 400. Succinct Encoding of Binary Tree
Source: https://en.wikipedia.org/wiki/Binary_tree#Succinct_encodings
Example:
Input:
10
/ \
20 30
/ \ \
40 50 70
Structure Array
1 1 1 0 0 1 0 0 1 0 1 0 0
1 indicates data and 0 indicates NULL
2366
Chapter 400. Succinct Encoding of Binary Tree
2367
Chapter 400. Succinct Encoding of Binary Tree
return NULL;
}
// A utility function to print tree
void preorder(Node* root)
{
if (root)
{
cout << "key: "<< root->key;
if (root->left)
cout << " | left child: " << root->left->key;
if (root->right)
cout << " | right child: " << root->right->key;
cout << endl;
preorder(root->left);
preorder(root->right);
}
}
// Driver program
int main()
{
// Let us construct the Tree shown in the above figure
Node *root = newNode(10);
root->left = newNode(20);
root->right = newNode(30);
root->left->left = newNode(40);
root->left->right = newNode(50);
root->right->right = newNode(70);
cout << "Given Tree\n";
preorder(root);
list<bool> struc;
list<int> data;
EncodeSuccinct(root, struc, data);
cout << "\nEncoded Tree\n";
cout << "Structure List\n";
list<bool>::iterator si; // Structure iterator
for (si = struc.begin(); si != struc.end(); ++si)
cout << *si << " ";
cout << "\nData List\n";
list<int>::iterator di; // Data iIterator
for (di = data.begin(); di != data.end(); ++di)
cout << *di << " ";
2368
Chapter 400. Succinct Encoding of Binary Tree
Python
2369
Chapter 400. Succinct Encoding of Binary Tree
#Create a tree node with removed data
root = Node(key)
#And recur to create left and right subtrees
root.left = DecodeSuccinct(struc , data);
root.right = DecodeSuccinct(struc , data);
return root
return None
def preorder(root):
if root is not None:
print "key: %d" %(root.key),
if root.left is not None:
print "| left child: %d" %(root.left.key),
if root.right is not None:
print "| right child %d" %(root.right.key),
print ""
preorder(root.left)
preorder(root.right)
# Driver Program
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.left.left = Node(40)
root.left.right = Node(50)
root.right.right = Node(70)
print "Given Tree"
preorder(root)
struc = []
data = []
EncodeSuccint(root , struc , data)
print "\nEncoded Tree"
print "Structure List"
for i in struc:
print i ,
print "\nDataList"
for value in data:
print value,
2370
Chapter 400. Succinct Encoding of Binary Tree
Output:
Given Tree
key: 10 | left child: 20 | right child: 30
key: 20 | left child: 40 | right child: 50
key: 40
key: 50
key: 30 | right child: 70
key: 70
Encoded Tree
Structure List
1 1 1 0 0 1 0 0 1 0 1 0 0
Data List
10 20 40 50 30 70
This article is contribute by Shivam. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Source
https://www.geeksforgeeks.org/succinct-encoding-of-binary-tree/
2371
Chapter 401
Approach: The approach to solve this problem is to construct the BST using insertion
method in BST. Once all the nodes are inserted, print the postorder traversal of the tree.
Below is the implementation of the above approach:
2372
Chapter 401. Sudo Placement[1.4] | BST Traversal
2373
Chapter 401. Sudo Placement[1.4] | BST Traversal
// data
cout << head->data << " ";
}
// Driver Code
int main()
{
Node* root = NULL;
root = insertNode(root, 8);
root = insertNode(root, 5);
root = insertNode(root, 10);
root = insertNode(root, 3);
root = insertNode(root, 4);
root = insertNode(root, 9);
root = insertNode(root, 7);
// prints the postorder traversal of
// the tree
posOrder(root);
cout << endl;
}
Source
https://www.geeksforgeeks.org/sudo-placement1-4-bst-traversal/
2374
Chapter 402
Input:
N = 7, Q = 2
BST elements: 8 4 10 15 14 88 64
Query1: 15
Query2: 88
Output: 8 4 10
8 4 10 15 14
8
/ \
4 10
\
15
/ \
14 88
/
64
2375
Chapter 402. Sudo Placement[1.4] | Jumping the Subtree
8
/ \
4 10
The preorder traversal of the above tree is: 8 4 10
A naive approach is to traverse the entire tree and store its pre-order traversal. In every
query, perform a pre-order traversal treating node as root. Print the entire tree’s pre-order
traversal except the elements that are in the pre-order traversal of the tree which treats
node as the root.
An efficient approach is to store the entire pre-order traversal of the tree in a container.
While finding the pre-order traversal of the tree, store the number of recursive calls from
the node and store it in a hash-table(mp). This effectively stores the entire size of the
subtree treating any node as the root. While performing every query, print the pre-order
traversal of the tree, till the node is found, once it is found, perform a jump of mp[node]
steps so that the subtree is skipped.
Below is the implementation of the above approach:
C++
2376
Chapter 402. Sudo Placement[1.4] | Jumping the Subtree
// structure to store the BST
struct Node {
int data;
Node* left = NULL;
Node* right = NULL;
};
// locates the memory space
Node* newNode(int key)
{
Node* temp = new Node;
temp->data = key;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// inserts node in the BST
Node* insertNode(Node* head, int key)
{
// if first node
if (head == NULL)
head = newNode(key);
else {
// move to left
if (key < head->data)
head->left = insertNode(head->left, key);
// move to right
else
head->right = insertNode(head->right, key);
}
return head;
}
// Function to compute the pre-order
// and compute the height of every sub-tree
int preOrder(Node* head)
{
// leaf node is null
if (head == NULL)
return 0;
pre.push_back(head->data);
mp[head->data] += preOrder(head->left);
mp[head->data] += preOrder(head->right);
2377
Chapter 402. Sudo Placement[1.4] | Jumping the Subtree
mp[head->data] += 1;
return mp[head->data];
}
// Function to perform every queries
void performQueries(int node)
{
// traverse in the pre-order
// jump the subtree which has node
for (int i = 0; i < pre.size();) {
// jump the subtree which has the node
if (pre[i] == node) {
i += mp[pre[i]];
}
// print the pre-order
else {
cout << pre[i] << " ";
i++;
}
}
cout << endl;
}
// Driver Code
int main()
{
Node* root = NULL;
/* 8
/ \
4 10
\
15
/ \
14 88
/
64 */
root = insertNode(root, 8);
root = insertNode(root, 4);
root = insertNode(root, 10);
root = insertNode(root, 15);
root = insertNode(root, 14);
2378
Chapter 402. Sudo Placement[1.4] | Jumping the Subtree
Java
2379
Chapter 402. Sudo Placement[1.4] | Jumping the Subtree
{
// move to left
if (key < head.data)
head.left = insertNode(head.left, key);
// move to right
else
head.right = insertNode(head.right, key);
}
return head;
}
public static int preOrder(Node head)
{
// leaf node is null
if (head == null)
return 0;
pre.add(head.data);
mp.put(head.data, head.data +
preOrder(head.left));
mp.put(head.data, head.data +
preOrder(head.right));
mp.put(head.data, head.data + 1);
return mp.get(head.data);
}
// Function to perform
// every queries
public static void performQueries(int node)
{
// traverse in the pre-order
// jump the subtree which has node
for (int i = 0; i < pre.size();)
{
// jump the subtree
// which has the node
if (pre.get(i) == node)
{
i += mp.get(pre.get(i));
}
// print the pre-order
2380
Chapter 402. Sudo Placement[1.4] | Jumping the Subtree
else
{
System.out.print(pre.get(i) + " ");
i++;
}
}
System.out.println();
}
public static void main (String[] args)
{
Node root = null;
/* 8
/ \
4 10
\
15
/ \
14 88
/
64 */
root = insertNode(root, 8);
root = insertNode(root, 4);
root = insertNode(root, 10);
root = insertNode(root, 15);
root = insertNode(root, 14);
root = insertNode(root, 88);
root = insertNode(root, 64);
// Pre-order traversal of tree
preOrder(root);
// Function call to
// perform queries
performQueries(15);
performQueries(88);
}
}
Output:
8 4 10
8 4 10 15 14
2381
Chapter 402. Sudo Placement[1.4] | Jumping the Subtree
Source
https://www.geeksforgeeks.org/sudo-placement1-4-jumping-the-subtree/
2382
Chapter 403
Input : 7 4
6 4 1 10 3 2 4
2 1 7
2 4 5
1 3 5
2 4 4
Output : 30
13
4
2383
Chapter 403. Sum of Interval and Update with Number of Divisors
Naive Approach :
A simple solution is to run a loop from l to r and calculate sum of elements in given range.
To update a value, precompute the values of number of divisors of every number and simply
do arr[i] = divisors[arr[i]].
Efficient Approach :
The idea is to reduce the time complexity for each query and update operation to O(logN).
Use Binary Indexed Trees (BIT) or Segment Trees. Construct a BIT[] array and have two
functions for query and update operation and precompute the number of divisors for each
number. Now, for each update operation the key observation is that the numbers ‘1’ and
‘2’ will have ‘1’ and ‘2’ as their number of divisors respectively, so if it exists in the range
of update query, they don’t need to be updated. We will use a set to store the index of
only those numbers which are greater than 2 and use binary search to find the l index of
the update query and increment the l index until every element is updated in range of that
update query. If the arr[i] has only 2 divisors then after updating it, remove it from the set
as it will always be 2 even after any next update query. For sum query operation, simply
do query(r) – query(l – 1).
2384
Chapter 403. Sum of Interval and Update with Number of Divisors
}
}
// function for calculating the required
// sum between two indexes
int sum(int x)
{
int s = 0;
for (x; x > 0; x -= x&-x) {
s += BIT[x];
}
return s;
}
// function to return answer to queries
void answerQueries(int arr[], queries que[], int n, int q)
{
// Declaring a Set
set<int> s;
for (int i = 1; i < n; i++) {
// inserting indexes of those numbers
// which are greater than 2
if(arr[i] > 2) s.insert(i);
update(i, arr[i], n);
}
for (int i = 0; i < q; i++) {
// update query
if (que[i].type == 1) {
while (true) {
// find the left index of query in
// the set using binary search
auto it = s.lower_bound(que[i].l);
// if it crosses the right index of
// query or end of set, then break
if(it == s.end() || *it > que[i].r) break;
que[i].l = *it;
// update the value of arr[i] to
// its number of divisors
update(*it, divisors[arr[*it]] - arr[*it], n);
arr[*it] = divisors[arr[*it]];
2385
Chapter 403. Sum of Interval and Update with Number of Divisors
// if updated value becomes less than or
// equal to 2 remove it from the set
if(arr[*it] <= 2) s.erase(*it);
// increment the index
que[i].l++;
}
}
// sum query
else {
cout << (sum(que[i].r) - sum(que[i].l - 1)) << endl;
}
}
}
// Driver Code
int main()
{
// precompute the number of divisors for each number
calcDivisors();
int q = 4;
// input array
int arr[] = {0, 6, 4, 1, 10, 3, 2, 4};
int n = sizeof(arr) / sizeof(arr[0]);
// declaring array of structure of type queries
queries que[q + 1];
que[0].type = 2, que[0].l = 1, que[0].r = 7;
que[1].type = 2, que[1].l = 4, que[1].r = 5;
que[2].type = 1, que[2].l = 3, que[2].r = 5;
que[3].type = 2, que[3].l = 4, que[3].r = 4;
// answer the Queries
answerQueries(arr, que, n, q);
return 0;
}
Output:
30
13
2386
Chapter 403. Sum of Interval and Update with Number of Divisors
Source
https://www.geeksforgeeks.org/sum-interval-update-number-divisors/
2387
Chapter 404
Example :
2388
Chapter 404. Sum of all elements of N-ary Tree
Approach : The approach used is similar to Level Order traversal in a binary tree. Start
by pushing the root node in the queue. And for each node, while popping it from queue,
add the value of this node in the sum variable and push the children of the popped element
in the queue. In case of a generic tree store child nodes in a vector. Thus, put all elements
of the vector in the queue.
Below is the implementation of the above idea :
2389
Chapter 404. Sum of all elements of N-ary Tree
// Dequeue an item from queue and
// add it to variable "sum"
Node* p = q.front();
q.pop();
sum += p->key;
// Enqueue all children of the dequeued item
for (int i = 0; i < p->child.size(); i++)
q.push(p->child[i]);
n--;
}
}
return sum;
}
// Driver program
int main()
{
// Creating a generic tree
Node* root = newNode(20);
(root->child).push_back(newNode(2));
(root->child).push_back(newNode(34));
(root->child).push_back(newNode(50));
(root->child).push_back(newNode(60));
(root->child).push_back(newNode(70));
(root->child[0]->child).push_back(newNode(15));
(root->child[0]->child).push_back(newNode(20));
(root->child[1]->child).push_back(newNode(30));
(root->child[2]->child).push_back(newNode(40));
(root->child[2]->child).push_back(newNode(100));
(root->child[2]->child).push_back(newNode(20));
(root->child[0]->child[1]->child).push_back(newNode(25));
(root->child[0]->child[1]->child).push_back(newNode(50));
cout << sumNodes(root) << endl;
return 0;
}
Output:
536
2390
Chapter 404. Sum of all elements of N-ary Tree
Source
https://www.geeksforgeeks.org/sum-elements-n-ary-tree/
2391
Chapter 405
Input :
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
Output :
Sum = 4 + 5 + 8 + 7 = 24
The idea is to traverse the tree in any fashion and check if the node is the leaf node or not.
If the node is the leaf node, add node data to sum variable.
Following is the implementation of above approach.
C++
2392
Chapter 405. Sum of all leaf nodes of binary tree
2393
Chapter 405. Sum of all leaf nodes of binary tree
Java
2394
Chapter 405. Sum of all leaf nodes of binary tree
Output:
24
Source
https://www.geeksforgeeks.org/sum-leaf-nodes-binary-tree/
2395
Chapter 406
C++
2396
Chapter 406. Sum of all nodes in a binary tree
Java
// Java Program to print sum of
// all the elements of a binary tree
class GFG
{
static class Node
{
int key;
Node left, right;
}
/* utility that allocates a new
Node with the given key */
2397
Chapter 406. Sum of all nodes in a binary tree
Improved By : andrew1234
Source
https://www.geeksforgeeks.org/sum-nodes-binary-tree/
2398
Chapter 407
Sum of all the numbers that are formed from root to leaf paths - GeeksforGeeks
Given a binary tree, where every node value is a Digit from 1-9 .Find the sum of all the
numbers which are formed from root to leaf paths.
For example consider the following Binary Tree.
6
/ \
3 5
/ \ \
2 5 4
\ /
7 4
There are 4 leaves, hence 4 root to leaf paths:
Path Number
6->3->2 632
6->3->5->7 6357
6->3->5->4 6354
6->5>4 654
Answer = 632 + 6357 + 6354 + 654 = 13997
The idea is to do a preorder traversal of the tree. In the preorder traversal, keep track of
the value calculated till the current node, let this value be val. For every node, we update
the val as val*10 plus node’s data.
C
2399
Chapter 407. Sum of all the numbers that are formed from root to leaf paths
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left, *right;
};
// function to allocate new node with given data
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Returns sum of all root to leaf paths. The first parameter is root
// of current subtree, the second parameter is value of the number formed
// by nodes from root to this node
int treePathsSumUtil(struct node *root, int val)
{
// Base case
if (root == NULL) return 0;
// Update val
val = (val*10 + root->data);
// if current node is leaf, return the current value of val
if (root->left==NULL && root->right==NULL)
return val;
// recur sum of values for left and right subtree
return treePathsSumUtil(root->left, val) +
treePathsSumUtil(root->right, val);
}
// A wrapper function over treePathsSumUtil()
int treePathsSum(struct node *root)
{
// Pass the initial value as 0 as there is nothing above root
return treePathsSumUtil(root, 0);
}
// Driver function to test the above functions
int main()
{
2400
Chapter 407. Sum of all the numbers that are formed from root to leaf paths
Java
// Java program to find sum of all numbers that are formed from root
// to leaf paths
// A binary tree node
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
// Returns sum of all root to leaf paths. The first parameter is
// root of current subtree, the second parameter is value of the
// number formed by nodes from root to this node
int treePathsSumUtil(Node node, int val)
{
// Base case
if (node == null)
return 0;
// Update val
val = (val * 10 + node.data);
// if current node is leaf, return the current value of val
if (node.left == null && node.right == null)
2401
Chapter 407. Sum of all the numbers that are formed from root to leaf paths
return val;
// recur sum of values for left and right subtree
return treePathsSumUtil(node.left, val)
+ treePathsSumUtil(node.right, val);
}
// A wrapper function over treePathsSumUtil()
int treePathsSum(Node node)
{
// Pass the initial value as 0 as there is nothing above root
return treePathsSumUtil(node, 0);
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(6);
tree.root.left = new Node(3);
tree.root.right = new Node(5);
tree.root.right.right = new Node(4);
tree.root.left.left = new Node(2);
tree.root.left.right = new Node(5);
tree.root.left.right.right = new Node(4);
tree.root.left.right.left = new Node(7);
System.out.print("Sum of all paths is " +
tree.treePathsSum(tree.root));
}
}
// This code has been contributed by Mayank Jaiswal
Python
2402
Chapter 407. Sum of all the numbers that are formed from root to leaf paths
Output:
Time Complexity: The above code is a simple preorder traversal code which visits every
exactly once. Therefore, the time complexity is O(n) where n is the number of nodes in the
given binary tree.
This article is contributed by Ramchand R. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
2403
Chapter 407. Sum of all the numbers that are formed from root to leaf paths
Source
https://www.geeksforgeeks.org/sum-numbers-formed-root-leaf-paths/
2404
Chapter 408
4
/ \
2 5
/ \ / \
7 2 2 3
Algorithm:
sumOfParentOfX(root,sum,x)
2405
Chapter 408. Sum of all the parent nodes having child node x
if root == NULL
return
sumOfParentOfX(root->left, sum, x)
sumOfParentOfX(root->right, sum, x)
sumOfParentOfXUtil(root,x)
Declare sum = 0
sumOfParentOfX(root, sum, x)
return sum
C++
2406
Chapter 408. Sum of all the parent nodes having child node x
if (!root)
return;
// if left or right child of root is 'x', then
// add the root's data to 'sum'
if ((root->left && root->left->data == x) ||
(root->right && root->right->data == x))
sum += root->data;
// recursively find the required parent nodes
// in the left and right subtree
sumOfParentOfX(root->left, sum, x);
sumOfParentOfX(root->right, sum, x);
}
// utility function to find the sum of all
// the parent nodes having child node x
int sumOfParentOfXUtil(Node* root, int x)
{
int sum = 0;
sumOfParentOfX(root, sum, x);
// required sum of parent nodes
return sum;
}
// Driver program to test above
int main()
{
// binary tree formation
Node *root = getNode(4); /* 4 */
root->left = getNode(2); /* / \ */
root->right = getNode(5); /* 2 5 */
root->left->left = getNode(7); /* / \ / \ */
root->left->right = getNode(2); /* 7 2 2 3 */
root->right->left = getNode(2);
root->right->right = getNode(3);
int x = 2;
cout << "Sum = "
<< sumOfParentOfXUtil(root, x);
return 0;
}
Java
2407
Chapter 408. Sum of all the parent nodes having child node x
2408
Chapter 408. Sum of all the parent nodes having child node x
Sum = 11
Source
https://www.geeksforgeeks.org/sum-parent-nodes-child-node-x/
2409
Chapter 409
2410
Chapter 409. Sum of heights of all individual nodes in a binary tree
2411
Chapter 409. Sum of heights of all individual nodes in a binary tree
Output:
Time Complexity : O(nh) where n is total number of nodes and h is height of binary tree.
Efficient Solution :
The idea is to compute heights and sum in same recursive call.
2412
Chapter 409. Sum of heights of all individual nodes in a binary tree
2413
Chapter 409. Sum of heights of all individual nodes in a binary tree
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Sum of heights of all Nodes = %d",
getTotalHeight(root));
return 0;
}
Output:
Time Complexity : O(nh) where n is total number of nodes and h is height of binary tree.
Improved By : akash1295
Source
https://www.geeksforgeeks.org/sum-heights-individual-nodes-binary-tree/
2414
Chapter 410
Input : K = 3
8
/ \
7 10
/ / \
2 9 13
Output : 32
Explanation: 3rd largest element is 9 so sum of all
elements greater than or equal to 9 are
9 + 10 + 13 = 32.
Input : K = 2
8
/ \
5 11
/ \
2 7
\
3
Output : 19
Explanation: 2nd largest element is 8 so sum of all
elements greater than or equal to 8 are
8 + 11 = 19.
2415
Chapter 410. Sum of k largest elements in BST
Approach:
The idea is to traverse BST in Inorder traversal in a reverse way (Right Root Left).
Note that Inorder traversal of BST accesses elements in a sorted (or increasing) order, hence
the reverse of inorder traversal will be in a sorted order(decreasing). While traversing, keep
track of the count of visited Nodes and keep adding Nodes until the count becomes k.
2416
Chapter 410. Sum of k largest elements in BST
{
// Base cases
if (root == NULL)
return 0;
if (c > k)
return 0;
// Compute sum of elements in right subtree
int ans = klargestElementSumUtil(root->right, k, c);
if (c >= k)
return ans;
// Add root's data
ans += root->data;
// Add current Node
c++;
if (c >= k)
return ans;
// If c is less than k, return left subtree Nodes
return ans + klargestElementSumUtil(root->left, k, c);
}
// Wrapper over klargestElementSumRec()
int klargestElementSum(struct Node* root, int k)
{
int c = 0;
klargestElementSumUtil(root, k, c);
}
// Drivers code
int main()
{
/* 19
/ \
7 21
/ \
3 11
/ \
9 13
*/
Node* root = NULL;
root = add(root, 19);
root = add(root, 7);
root = add(root, 3);
root = add(root, 11);
2417
Chapter 410. Sum of k largest elements in BST
Output:
40
Source
https://www.geeksforgeeks.org/sum-of-k-largest-elements-in-bst/
2418
Chapter 411
Input :
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
Output : 11
Leaf nodes 4 and 7 are at minimum level.
Their sum = (4 + 7) = 11.
2419
Chapter 411. Sum of leaf nodes at minimum level
2420
Chapter 411. Sum of leaf nodes at minimum level
// get front element from 'q'
Node* top = q.front();
q.pop();
// if it is a leaf node
if (!top->left && !top->right) {
// accumulate data to 'sum'
sum += top->data;
// set flag 'f' to 1, to signify
// minimum level for leaf nodes
// has been encountered
f = 1;
}
else {
// if top's left and right child
// exists, then push them to 'q'
if (top->left)
q.push(top->left);
if (top->right)
q.push(top->right);
}
}
}
// required sum
return sum;
}
// Driver program to test above
int main()
{
// binary tree creation
Node* root = getNode(1);
root->left = getNode(2);
root->right = getNode(3);
root->left->left = getNode(4);
root->left->right = getNode(5);
root->right->left = getNode(6);
root->right->right = getNode(7);
root->left->right->left = getNode(8);
root->right->left->right = getNode(9);
cout << "Sum = "
<< sumOfLeafNodesAtMinLevel(root);
2421
Chapter 411. Sum of leaf nodes at minimum level
return 0;
}
Output:
Sum = 11
Source
https://www.geeksforgeeks.org/sum-leaf-nodes-minimum-level/
2422
Chapter 412
2423
Chapter 412. Sum of nodes at k-th level in a tree represented as string
--> level++
3.2 else if ch == ')' then
--> level--
3.3 else
if level == k then
sum = sum + (ch-'0')
4. Print sum
2424
Chapter 412. Sum of nodes at k-th level in a tree represented as string
int k = 2;
cout << sumAtKthLevel(tree, k);
return 0;
}
Output:
14
Source
https://www.geeksforgeeks.org/sum-nodes-k-th-level-tree-represented-string/
2425
Chapter 413
1
/ \
2 3
/ \ / \
4 5 6 7
Explanation:
Nodes at maximum depth are: 4, 5, 6, 7.
So, sum of these nodes = 22
Approach: Calculate the max depth of the given tree. Now, start traversing the tree
similarly as traversed during maximum depth calculation. But, this time with one more
argument (i.e. maxdepth), and traverse recursively with decreasing depth by 1 for each left
or right call. Wherever max == 1, means the node at max depth is reached. So add its
data value to sum. Finally, return sum.
Below is the implementation for above approach:
2426
Chapter 413. Sum of nodes at maximum depth of a Binary Tree
// at maximum depth
import java.util.*;
class Node {
int data;
Node left, right;
// Constructor
public Node(int data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
class GfG {
// function to find the sum of nodes at
// maximum depth arguments are node and
// max, where max is to match the depth
// of node at every call to node, if
// max will be equal to 1, means
// we are at deepest node.
public static int sumMaxLevelRec(Node node,
int max)
{
// base case
if (node == null)
return 0;
// max == 1 to track the node
// at deepest level
if (max == 1)
return node.data;
// recursive call to left and right nodes
return sumMaxLevelRec(node.left, max - 1) +
sumMaxLevelRec(node.right, max - 1);
}
public static int sumMaxLevel(Node root) {
// call to function to calculate
// max depth
int MaxDepth = maxDepth(root);
return sumMaxLevelRec(root, MaxDepth);
2427
Chapter 413. Sum of nodes at maximum depth of a Binary Tree
}
// maxDepth function to find the
// max depth of the tree
public static int maxDepth(Node node)
{
// base case
if (node == null)
return 0;
// either leftDepth of rightDepth is
// greater add 1 to include height
// of node at which call is
return 1 + Math.max(maxDepth(node.left),
maxDepth(node.right));
}
// Driver code
public static void main(String[] args)
{
/* 1
/ \
2 3
/ \ / \
4 5 6 7 */
// Constructing tree
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
// call to calculate required sum
System.out.println(sumMaxLevel(root));
}
}
Output :
22
2428
Chapter 413. Sum of nodes at maximum depth of a Binary Tree
Source
https://www.geeksforgeeks.org/sum-nodes-maximum-depth-binary-tree/
2429
Chapter 414
1
/ \
2 3
/ \ / \
4 5 6 7
Explanation:
Nodes at maximum depth are 4, 5, 6, 7.
So, the sum of these nodes = 22
Approach: There exists a recursive approach to this problem. This can also be solved
using level order traversal and map. The idea is to do a traversal using a queue and keep
track of current level. A map has been used to store the sum of nodes at the current level.
Once all nodes are visited and the traversal is done, the last element of the map will contain
the sum at the maximum depth of the tree.
Below is the implementation of the above approach:
2430
Chapter 414. Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
2431
Chapter 414. Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
Output:
22
Source
https://www.geeksforgeeks.org/sum-of-nodes-at-maximum-depth-of-a-binary-tree-iterative-approach/
2432
Chapter 415
Sum of nodes on the longest path from root to leaf node - GeeksforGeeks
Given a binary tree containing n nodes. The problem is to find the sum of all nodes on
the longest path from root to leaf node. If two or more paths compete for the longest path,
then the path having maximum sum of nodes is being considered.
Examples:
4
/ \
2 5
/ \ / \
7 1 2 3
/
6
2433
Chapter 415. Sum of nodes on the longest path from root to leaf node
Approach: Recursively find the length and sum of nodes of each root to leaf path and
accordingly update the maximum sum.
Algorithm:
sumOfLongRootToLeafPathUtil(root)
if (root == NULL)
return 0
C++
2434
Chapter 415. Sum of nodes on the longest path from root to leaf node
// put in the data
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// function to find the sum of nodes on the
// longest path from root to leaf node
void sumOfLongRootToLeafPath(Node* root, int sum,
int len, int& maxLen, int& maxSum)
{
// if true, then we have traversed a
// root to leaf path
if (!root) {
// update maximum length and maximum sum
// according to the given conditions
if (maxLen < len) {
maxLen = len;
maxSum = sum;
} else if (maxLen == len && maxSum < sum)
maxSum = sum;
return;
}
// recur for left subtree
sumOfLongRootToLeafPath(root->left, sum + root->data,
len + 1, maxLen, maxSum);
// recur for right subtree
sumOfLongRootToLeafPath(root->right, sum + root->data,
len + 1, maxLen, maxSum);
}
// utility function to find the sum of nodes on
// the longest path from root to leaf node
int sumOfLongRootToLeafPathUtil(Node* root)
{
// if tree is NULL, then sum is 0
if (!root)
return 0;
int maxSum = INT_MIN, maxLen = 0;
// finding the maximum sum 'maxSum' for the
// maximum length root to leaf path
sumOfLongRootToLeafPath(root, 0, 0, maxLen, maxSum);
2435
Chapter 415. Sum of nodes on the longest path from root to leaf node
Java
2436
Chapter 415. Sum of nodes on the longest path from root to leaf node
2437
Chapter 415. Sum of nodes on the longest path from root to leaf node
Output:
Sum = 13
Source
https://www.geeksforgeeks.org/sum-nodes-longest-path-root-leaf-node/
2438
Chapter 416
1 Level 1
2439
Chapter 416. Swap Nodes in Binary tree of every k’th level
/ \
2 3 Level 2
/ \
4 5 Level 3
Output : Root of the following modified tree
1
/ \
3 2
/ \
5 4
Since k is 1, we need to swap sibling nodes of
all levels.
A simple solution of this problem is that for each is to find sibling nodes for each multiple
of k and swap them.
An efficient solution is to keep track of level number in recursive calls. And for every
node being visited, check if level number of its children is a multiple of k. If yes, then swap
the two children of the node. Else, recur for left and right children.
Below is C++ implementation of above idea
C++
2440
Chapter 416. Swap Nodes in Binary tree of every k’th level
*a = *b;
*b = temp;
}
// A utility function swap left- node & right node of tree
// of every k'th level
void swapEveryKLevelUtil( Node *root, int level, int k)
{
// base case
if (root== NULL ||
(root->left==NULL && root->right==NULL) )
return ;
//if current level + 1 is present in swap vector
//then we swap left & right node
if ( (level + 1) % k == 0)
Swap(&root->left, &root->right);
// Recur for left and right subtrees
swapEveryKLevelUtil(root->left, level+1, k);
swapEveryKLevelUtil(root->right, level+1, k);
}
// This function mainly calls recursive function
// swapEveryKLevelUtil()
void swapEveryKLevel(Node *root, int k)
{
// call swapEveryKLevelUtil function with
// initial level as 1.
swapEveryKLevelUtil(root, 1, k);
}
// Utility method for inorder tree traversal
void inorder(Node *root)
{
if (root == NULL)
return;
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
// Driver Code
int main()
{
/* 1
/ \
2 3
2441
Chapter 416. Swap Nodes in Binary tree of every k’th level
/ / \
4 7 8 */
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->right->right = newNode(8);
root->right->left = newNode(7);
int k = 2;
cout << "Before swap node :"<<endl;
inorder(root);
swapEveryKLevel(root, k);
cout << "\nAfter swap Node :" << endl;
inorder(root);
return 0;
}
Python
2442
Chapter 416. Swap Nodes in Binary tree of every k’th level
swapEveryKLevelUtil(root.left, level+1, k)
swapEveryKLevelUtil(root.right, level+1, k)
# This function mainly calls recursive function
# swapEveryKLevelUtil
def swapEveryKLevel(root, k):
# Call swapEveryKLevelUtil function with
# initial level as 1
swapEveryKLevelUtil(root, 1, k)
# Method to find the inorder tree travesal
def inorder(root):
# Base Case
if root is None:
return
inorder(root.left)
print root.data,
inorder(root.right)
# Driver code
"""
1
/ \
2 3
/ / \
4 7 8
"""
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.right = Node(8)
root.right.left = Node(7)
k = 2
print "Before swap node :"
inorder(root)
swapEveryKLevel(root, k)
print "\nAfter swap Node : "
inorder(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
2443
Chapter 416. Swap Nodes in Binary tree of every k’th level
Output:
Source
https://www.geeksforgeeks.org/swap-nodes-binary-tree-every-kth-level/
2444
Chapter 417
1
/ \
2 2
/ \ / \
3 4 4 3
1
/ \
2 2
\ \
3 3
The idea is to write a recursive function isMirror() that takes two trees as argument and
returns true if trees are mirror and false if trees are not mirror. The isMirror() function
recursively checks two roots and subtrees under the root.
Below is implementation of above algorithm.
C++
2445
Chapter 417. Symmetric Tree (Mirror Image of itself)
2446
Chapter 417. Symmetric Tree (Mirror Image of itself)
}
// Driver program
int main()
{
// Let us construct the Tree shown in the above figure
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(2);
root->left->left = newNode(3);
root->left->right = newNode(4);
root->right->left = newNode(4);
root->right->right = newNode(3);
cout << isSymmetric(root);
return 0;
}
Java
2447
Chapter 417. Symmetric Tree (Mirror Image of itself)
Python
2448
Chapter 417. Symmetric Tree (Mirror Image of itself)
# Utility function to create new node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Returns True if trees with roots as root1 and root 2
# are mirror
def isMirror(root1 , root2):
# If both trees are empty, then they are mirror images
if root1 is None and root2 is None:
return True
""" For two trees to be mirror images, the following three
conditions must be true
1 - Their root node's key must be same
2 - left subtree of left tree and right subtree
of right tree have to be mirror images
3 - right subtree of left tree and left subtree
of right tree have to be mirror images
"""
if (root1 is not None and root2 is not None):
if root1.key == root2.key:
return (isMirror(root1.left, root2.right)and
isMirror(root1.right, root2.left))
# If neither of above conditions is true then root1
# and root2 are not mirror images
return False
def isSymmetric(root):
# Check if tree is mirror of itself
return isMirror(root, root)
# Driver Program
# Let's construct the tree show in the above figure
root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(4)
root.right.right = Node(3)
print "1" if isSymmetric(root) == True else "0"
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
2449
Chapter 417. Symmetric Tree (Mirror Image of itself)
Output:
Source
https://www.geeksforgeeks.org/symmetric-tree-tree-which-is-mirror-image-of-itself/
2450
Chapter 418
2451
Chapter 418. Ternary Search Tree (Deletion)
1. Let suppose we want to delete string “BIG”,since it is not present in TST so after
matching with first character ‘B’, delete_node function will return zero. Hence nothing
is deleted.
2. Now we want to delete string “BUG”, it is Uniquely present in TST i.e neither it has
part which is the prefix of other string nor it is prefix to any other string, so it will be
deleted completely.
3. Now we want to delete string “CAT”, since it is prefix of string “CATS”, we cannot
delete anthing from the string “CAT” and we can only unmark the leaf node which
will ensure that “CAT” is no longer a member string of TST.
4. Now we want to delete string “CATS”, since it has a prefix string “CAT” which also is
a member string of TST so we can only delete last character of string “CATS” which
will ensure that string “CAT” still remains the part of TST.
2452
Chapter 418. Ternary Search Tree (Deletion)
2453
Chapter 418. Ternary Search Tree (Deletion)
2454
Chapter 418. Ternary Search Tree (Deletion)
{
// Unmark leaf node if present
if (isLeaf(root))
{
root->isleaf=0;
return isFreeNode(root);
}
// else string is not present in TST and
// return 0
else
return 0;
}
else
{
// CASE 3 Key is prefix key of another
// long key in TST.
if (str[level] < root->key)
delete_node(root->left ,str ,level ,n);
else if (str[level] > root->key)
delete_node(root->right ,str ,level ,n);
// CASE 1 Key may not be there in TST.
else if (str[level] == root->key)
{
// CASE 2 Key present as unique key
if( delete_node(root->eq ,str ,level+1 ,n) )
{
// delete the last node, neither it
// has any child
// nor it is part of any other string
free(root->eq);
return !isLeaf(root) && isFreeNode(root);
}
}
}
return 0;
}
// Driver function
int main()
{
struct Node *temp = NULL;
insert_node(&temp ,"CAT");
insert_node(&temp ,"BUGS");
insert_node(&temp ,"CATS");
2455
Chapter 418. Ternary Search Tree (Deletion)
insert_node(&temp ,"UP");
int level = 0;
char str[20];
int p = 0;
printf( "1.Content of the TST before "
"deletion:\n" );
display(temp ,str ,level);
level = 0;
delete_node(temp ,"CAT" ,level ,5);
level = 0;
printf("\n2.Content of the TST after "
"deletion:\n");
display(temp, str, level);
return 0;
}
C++
2456
Chapter 418. Ternary Search Tree (Deletion)
temp->right = NULL;
return temp;
};
// function to insert a Node in TST
void insert_node(struct Node **root, char *s)
{
if (!(*root))
{
(*root) = createNode(*s);
}
if ((*s)<(*root)->key)
insert_node( &(*root)->left, s);
else if ((*s)>(*root)->key)
insert_node( &(*root)->right, s);
else if ((*s) == (*root)->key)
{
if (*(s+1) == '\0')
{
(*root)->isleaf = 1;
return;
}
insert_node( &(*root)->eq, s+1);
}
}
// function to display the TST
void display(struct Node *root, char str[], int level)
{
if (!root)
return;
display(root->left, str, level);
str[level] = root->key;
if (root->isleaf == 1)
{
str[level+1] = '\0';
cout<< str <<endl;
}
display(root->eq, str, level+1);
display(root->right, str, level);
}
2457
Chapter 418. Ternary Search Tree (Deletion)
2458
Chapter 418. Ternary Search Tree (Deletion)
Output:
2459
Chapter 418. Ternary Search Tree (Deletion)
CATS
UP
Source
https://www.geeksforgeeks.org/ternary-search-tree-deletion/
2460
Chapter 419
Source
https://www.geeksforgeeks.org/the-great-tree-list-recursion-problem/
2461
Chapter 420
struct Node
2462
Chapter 420. Threaded Binary Tree
{
int data;
Node *left, *right;
bool rightThread;
}
Since right pointer is used for two purposes, the boolean variable rightThread is used to
indicate whether right pointer points to right child or inorder successor. Similarly, we can
add leftThread for a double threaded binary tree.
Inorder Taversal using Threads
Following is C code for inorder traversal in a threaded binary tree.
2463
Chapter 420. Threaded Binary Tree
2464
Chapter 420. Threaded Binary Tree
Source
https://www.geeksforgeeks.org/threaded-binary-tree/
2465
Chapter 421
struct Node
{
struct Node *left, *right;
int info;
In the following explanation, we have considered Binary Search Tree (BST) for insertion as
insertion is defined by some rules in BSTs.
Let tmp be the newly inserted node. There can be three cases during insertion:
Case 1: Insertion in empty tree
Both left and right pointers of tmp will be set to NULL and new node becomes the root.
2466
Chapter 421. Threaded Binary Tree | Insertion
root = tmp;
tmp -> left = NULL;
tmp -> right = NULL;
Before insertion, the left pointer of parent was a thread, but after insertion it will be a link
pointing to the new node.
Following example show a node being inserted as left child of its parent.
2467
Chapter 421. Threaded Binary Tree | Insertion
Before insertion, the right pointer of parent was a thread, but after insertion it will be a
link pointing to the new node.
Following example shows a node being inserted as right child of its parent.
2468
Chapter 421. Threaded Binary Tree | Insertion
After 15 inserted,
2469
Chapter 421. Threaded Binary Tree | Insertion
2470
Chapter 421. Threaded Binary Tree | Insertion
{
tmp -> left = par -> left;
tmp -> right = par;
par -> lthread = false;
par -> left = tmp;
}
else
{
tmp -> left = par;
tmp -> right = par -> right;
par -> rthread = false;
par -> right = tmp;
}
return root;
}
// Returns inorder successor using rthread
struct Node *inorderSuccessor(struct Node *ptr)
{
// If rthread is set, we can quickly find
if (ptr -> rthread == true)
return ptr->right;
// Else return leftmost child of right subtree
ptr = ptr -> right;
while (ptr -> lthread == false)
ptr = ptr -> left;
return ptr;
}
// Printing the threaded tree
void inorder(struct Node *root)
{
if (root == NULL)
printf("Tree is empty");
// Reach leftmost node
struct Node *ptr = root;
while (ptr -> lthread == false)
ptr = ptr -> left;
// One by one print successors
while (ptr != NULL)
{
printf("%d ",ptr -> info);
ptr = inorderSuccessor(ptr);
}
2471
Chapter 421. Threaded Binary Tree | Insertion
}
// Driver Program
int main()
{
struct Node *root = NULL;
root = insert(root, 20);
root = insert(root, 10);
root = insert(root, 30);
root = insert(root, 5);
root = insert(root, 16);
root = insert(root, 14);
root = insert(root, 17);
root = insert(root, 13);
inorder(root);
return 0;
}
Output:
5 10 13 14 16 17 20 30
Source
https://www.geeksforgeeks.org/threaded-binary-tree-insertion/
2472
Chapter 422
Input :
1
/ \
2 3
Output : 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
Input :
4
/ \
2 9
/ \ \
3 5 7
Output : 15
Explanation:
Tilt of node 3 : 0
Tilt of node 5 : 0
Tilt of node 7 : 0
Tilt of node 2 : |3-5| = 2
2473
Chapter 422. Tilt of Binary Tree
The idea is to recursively traverse tree. While traversing, we keep track of two things, sum
of subtree rooted under current node, tilt of current node. Sum is needed to compute tilt
of parent.
2474
Chapter 422. Tilt of Binary Tree
Output:
Complexity Analysis:
Source
https://www.geeksforgeeks.org/tilt-binary-tree/
2475
Chapter 423
Input :
1
/ \
2 3
/ \ / \
4 5 4 5
Output :Three largest elements are 5 4 3
Approach We can simply take three variables first, second, third to store the first largest,
second largest, third largest respectively and perform preorder traversal and each time we
will update the elements accordingly.
This approach will take O(n) time only.
Algorithm-
2476
Chapter 423. Top three elements in binary tree
2477
Chapter 423. Top three elements in binary tree
Output:
Source
https://www.geeksforgeeks.org/top-three-elements-binary-tree/
2478
Chapter 424
Input:
2479
Chapter 424. Total nodes traversed in Euler Tour Tree
Output: 15
Input:
Output: 17
Explanation:
Using Example 1:
2480
Chapter 424. Total nodes traversed in Euler Tour Tree
where
It can be seen that each node’s count in Euler Tour is exactly equal
to the out-degree of node plus 1.
2481
Chapter 424. Total nodes traversed in Euler Tour Tree
Where
Total represents total number of nodes in Euler Tour Tree
2482
Chapter 424. Total nodes traversed in Euler Tour Tree
add_edge(2, 5);
add_edge(3, 6);
add_edge(3, 7);
add_edge(6, 8);
// Out_deg[node[i]] is equal to adj[i].size()
checkTotalNumberofNodes(2 * N - 1, N);
// clear previous stored tree
for (int i = 1; i <= N; i++)
adj[i].clear();
// Constructing 2nd tree from example
N = 9;
add_edge(1, 2);
add_edge(1, 3);
add_edge(2, 4);
add_edge(2, 5);
add_edge(2, 6);
add_edge(3, 9);
add_edge(5, 7);
add_edge(5, 8);
// Out_deg[node[i]] is equal to adj[i].size()
checkTotalNumberofNodes(2 * N - 1, N);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/total-nodes-traversed-in-euler-tour-tree/
2483
Chapter 425
2484
Chapter 425. Total sum except adjacent of a given node in a Binary Tree
3. If current node is the key then do not add it’s children to the final sum.
4. If key is not present then return sum of all nodes.
C++
2485
Chapter 425. Total sum except adjacent of a given node in a Binary Tree
root->left = getNode(13);
root->left->left = getNode(12);
root->left->left->left = getNode(11);
root->left->right = getNode(14);
root->right = getNode(20);
root->right->left = getNode(18);
root->right->right = getNode(24);
root->right->right->left = getNode(23);
root->right->right->right = getNode(25);
int key = 20;
int sum = 0;
find_sum(root, key, sum, true);
printf("%d ", sum);
return 0;
}
Java
2486
Chapter 425. Total sum except adjacent of a given node in a Binary Tree
{
r.sum -= root.data;
}
else
if((root.right != null) && (root.right.data == key))
{
r.sum -= root.data;
}
}
if(root.data == key)
incl = false;
else
incl = true;
find_sum(root.left, key, r, incl);
find_sum(root.right, key, r, incl);
}
}
// Driver code
public static void main (String[] args)
{
Node root = new Node(15);
root.left = new Node(13);
root.left.left = new Node(12);
root.left.left.left = new Node(11);
root.left.right = new Node(14);
root.right = new Node(20);
root.right.left = new Node(18);
root.right.right = new Node(24);
root.right.right.right = new Node(25);
root.right.right.left = new Node(23);
int key = 20;
cal obj = new cal();
find_sum(root, key, obj, true);
System.out.print(obj.sum);
}
}
Output:
118
2487
Chapter 425. Total sum except adjacent of a given node in a Binary Tree
Source
https://www.geeksforgeeks.org/total-sum-except-adjacent-of-a-given-node-in-a-binary-tree/
2488
Chapter 426
Traversal of tree with k jumps allowed between nodes of same height - GeeksforGeeks
Consider a tree with n nodes and root. You can jump from one node to any other node on
the same height a maximum of k times on total jumps. Certain nodes of the tree contain a
fruit, find out the maximum number of fruits he can collect.
Example :
Input Tree :
Number of Nodes = 12
Number of jumps allowed : 2
Edges:
1 2
1 3
2 4
2 5
5 9
9 10
9 11
11 12
1 3
3 7
7 6
7 8
Nodes Containing Fruits : 2 4 5 7 8 9 11 12
Output: 7
2489
Chapter 426. Traversal of tree with k jumps allowed between nodes of same height
Explanation:
2490
Chapter 426. Traversal of tree with k jumps allowed between nodes of same height
Approach: The idea is to use DFS to create a Height Adjacency List of the Nodes and to
store the parents. Then use another dfs to compute the maximum no of special nodes that
can be reached using the following dp state:
2491
Chapter 426. Traversal of tree with k jumps allowed between nodes of same height
int Fruit[N];
int Parent[N];
int dp[N][20];
// Function for DFS
void dfs1(vector<int> tree[], int s,
int p, int h)
{
Parent[s] = p;
int i;
H[h].push_back(s);
for (i = 0; i < tree[s].size(); i++) {
int v = tree[s][i];
if (v != p)
dfs1(tree, v, s, h + 1);
}
}
// Function for DFS
int dfs2(vector<int> tree[], int s,
int p, int h, int j)
{
int i;
int ans = 0;
if (dp[s][j] != -1)
return dp[s][j];
// jump
if (j > 0) {
for (i = 0; i < H[h].size(); i++) {
int v = H[h][i];
if (v != s)
ans = max(ans, dfs2(tree, v,
Parent[v], h, j - 1));
}
}
// climb
for (i = 0; i < tree[s].size(); i++) {
int v = tree[s][i];
if (v != p)
ans = max(ans, dfs2(tree, v, s, h + 1, j));
}
if (Fruit[s] == 1)
ans++;
dp[s][j] = ans;
2492
Chapter 426. Traversal of tree with k jumps allowed between nodes of same height
return ans;
}
// Function to calculate and
// return maximum number of fruits
int maxFruit(vector<int> tree[],
int NodesWithFruits[],
int n, int m, int k)
{
// reseting dp table and Fruit array
for (int i = 0; i < N; i++) {
for (int j = 0; j < 20; j++)
dp[i][j] = -1;
Fruit[i] = 0;
}
// This array is used to mark
// which nodes contain Fruits
for (int i = 0; i < m; i++)
Fruit[NodesWithFruits[i]] = 1;
dfs1(tree, 1, 0, 0);
int ans = dfs2(tree, 1, 0, 0, k);
return ans;
}
// Function to add Edge
void addEdge(vector<int> tree[], int u, int v)
{
tree[u].push_back(v);
tree[v].push_back(u);
}
// Driver Code
int main()
{
int n = 12; // Number of nodes
int k = 2; // Number of allowed jumps
vector<int> tree[N];
// Edges
addEdge(tree, 1, 2);
addEdge(tree, 1, 3);
addEdge(tree, 2, 4);
addEdge(tree, 2, 5);
addEdge(tree, 5, 9);
2493
Chapter 426. Traversal of tree with k jumps allowed between nodes of same height
addEdge(tree, 9, 10);
addEdge(tree, 9, 11);
addEdge(tree, 11, 12);
addEdge(tree, 1, 3);
addEdge(tree, 3, 7);
addEdge(tree, 7, 6);
addEdge(tree, 7, 8);
int NodesWithFruits[] = { 2, 4, 5, 7, 8, 9, 11, 12 };
// Number of nodes with fruits
int m = sizeof(NodesWithFruits) / sizeof(NodesWithFruits[0]);
int ans = maxFruit(tree, NodesWithFruits, n, m, k);
cout << ans << endl;
return 0;
}
Output:
Time Complexity : O(n*n*k) (worst case, eg: 2 level tree with the root having n-1 child
nodes)
Source
https://www.geeksforgeeks.org/traversal-tree-ability-jump-nodes-height/
2494
Chapter 427
We simultaneously traverse both trees. Let the current internal nodes of two trees being
traversed be n1 and n2 respectively. There are following two conditions for subtrees rooted
with n1 and n2 to be isomorphic.
1) Data of n1 and n2 is same.
2) One of the following two is true for children of n1 and n2
……a) Left child of n1 is isomorphic to left child of n2 and right child of n1 is isomorphic to
right child of n2.
……b) Left child of n1 is isomorphic to right child of n2 and right child of n1 is isomorphic
to left child of n2.
C++
2495
Chapter 427. Tree Isomorphism Problem
2496
Chapter 427. Tree Isomorphism Problem
int main()
{
// Let us create trees shown in above diagram
struct node *n1 = newNode(1);
n1->left = newNode(2);
n1->right = newNode(3);
n1->left->left = newNode(4);
n1->left->right = newNode(5);
n1->right->left = newNode(6);
n1->left->right->left = newNode(7);
n1->left->right->right = newNode(8);
struct node *n2 = newNode(1);
n2->left = newNode(3);
n2->right = newNode(2);
n2->right->left = newNode(4);
n2->right->right = newNode(5);
n2->left->right = newNode(6);
n2->right->right->left = newNode(8);
n2->right->right->right = newNode(7);
if (isIsomorphic(n1, n2) == true)
cout << "Yes";
else
cout << "No";
return 0;
}
Java
2497
Chapter 427. Tree Isomorphism Problem
2498
Chapter 427. Tree Isomorphism Problem
Python
2499
Chapter 427. Tree Isomorphism Problem
)
# Driver program to test above function
n1 = Node(1)
n1.left = Node(2)
n1.right = Node(3)
n1.left.left = Node(4)
n1.left.right = Node(5)
n1.right.left = Node(6)
n1.left.right.left = Node(7)
n1.left.right.right = Node(8)
n2 = Node(1)
n2.left = Node(3)
n2.right = Node(2)
n2.right.left = Node(4)
n2.right.right = Node(5)
n2.left.right = Node(6)
n2.right.right.left = Node(8)
n2.right.right.right = Node(7)
print "Yes" if (isIsomorphic(n1, n2) == True) else "No"
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Yes
Time Complexity: The above solution does a traversal of both trees. So time complexity
is O(m + n) where m and n are number of nodes in given trees.
Source
https://www.geeksforgeeks.org/tree-isomorphism-problem/
2500
Chapter 428
Example Tree
Depth First Traversals:
(a) Inorder (Left, Root, Right) : 4 2 5 1 3
(b) Preorder (Root, Left, Right) : 1 2 4 5 3
(c) Postorder (Left, Right, Root) : 4 5 2 3 1
Breadth First or Level Order Traversal : 1 2 3 4 5
Please see thispost for Breadth First Traversal.
Inorder Traversal (Practice):
Algorithm Inorder(tree)
1. Traverse the left subtree, i.e., call Inorder(left-subtree)
2501
Chapter 428. Tree Traversals (Inorder, Preorder and Postorder)
Uses of Inorder
In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order.
To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder
traversal s reversed can be used.
Example: Inorder traversal for the above-given figure is 4 2 5 1 3.
Algorithm Preorder(tree)
1. Visit the root.
2. Traverse the left subtree, i.e., call Preorder(left-subtree)
3. Traverse the right subtree, i.e., call Preorder(right-subtree)
Uses of Preorder
Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get
prefix expression on of an expression tree. Please see http://en.wikipedia.org/wiki/Polish_
notation to know why prefix expressions are useful.
Example: Preorder traversal for the above given figure is 1 2 4 5 3.
Algorithm Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
Uses of Postorder
Postorder traversal is used to delete the tree. Please see the question for deletion of tree
for details. Postorder traversal is also useful to get the postfix expression of an expression
tree. Please see http://en.wikipedia.org/wiki/Reverse_Polish_notation to for the usage of
postfix expression.
Example: Postorder traversal for the above given figure is 4 5 2 3 1.
C++
2502
Chapter 428. Tree Traversals (Inorder, Preorder and Postorder)
2503
Chapter 428. Tree Traversals (Inorder, Preorder and Postorder)
2504
Chapter 428. Tree Traversals (Inorder, Preorder and Postorder)
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Given a binary tree, print its nodes according to the
"bottom-up" postorder traversal. */
void printPostorder(struct node* node)
{
if (node == NULL)
return;
// first recur on left subtree
printPostorder(node->left);
// then recur on right subtree
printPostorder(node->right);
// now deal with the node
printf("%d ", node->data);
}
/* Given a binary tree, print its nodes in inorder*/
void printInorder(struct node* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);
/* then print the data of node */
printf("%d ", node->data);
/* now recur on right child */
printInorder(node->right);
}
/* Given a binary tree, print its nodes in preorder*/
2505
Chapter 428. Tree Traversals (Inorder, Preorder and Postorder)
Python
2506
Chapter 428. Tree Traversals (Inorder, Preorder and Postorder)
# A function to do inorder tree traversal
def printInorder(root):
if root:
# First recur on left child
printInorder(root.left)
# then print the data of node
print(root.val),
# now recur on right child
printInorder(root.right)
# A function to do postorder tree traversal
def printPostorder(root):
if root:
# First recur on left child
printPostorder(root.left)
# the recur on right child
printPostorder(root.right)
# now print the data of node
print(root.val),
# A function to do preorder tree traversal
def printPreorder(root):
if root:
# First print the data of node
print(root.val),
# Then recur on left child
printPreorder(root.left)
# Finally recur on right child
printPreorder(root.right)
2507
Chapter 428. Tree Traversals (Inorder, Preorder and Postorder)
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "Preorder traversal of binary tree is"
printPreorder(root)
print "\nInorder traversal of binary tree is"
printInorder(root)
print "\nPostorder traversal of binary tree is"
printPostorder(root)
Java
2508
Chapter 428. Tree Traversals (Inorder, Preorder and Postorder)
return;
// first recur on left subtree
printPostorder(node.left);
// then recur on right subtree
printPostorder(node.right);
// now deal with the node
System.out.print(node.key + " ");
}
/* Given a binary tree, print its nodes in inorder*/
void printInorder(Node node)
{
if (node == null)
return;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
System.out.print(node.key + " ");
/* now recur on right child */
printInorder(node.right);
}
/* Given a binary tree, print its nodes in preorder*/
void printPreorder(Node node)
{
if (node == null)
return;
/* first print data of node */
System.out.print(node.key + " ");
/* then recur on left sutree */
printPreorder(node.left);
/* now recur on right subtree */
printPreorder(node.right);
}
// Wrappers over above recursive functions
void printPostorder() { printPostorder(root); }
void printInorder() { printInorder(root); }
void printPreorder() { printPreorder(root); }
2509
Chapter 428. Tree Traversals (Inorder, Preorder and Postorder)
// Driver method
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("Preorder traversal of binary tree is ");
tree.printPreorder();
System.out.println("\nInorder traversal of binary tree is ");
tree.printInorder();
System.out.println("\nPostorder traversal of binary tree is ");
tree.printPostorder();
}
}
Output:
2510
Chapter 428. Tree Traversals (Inorder, Preorder and Postorder)
2511
Chapter 428. Tree Traversals (Inorder, Preorder and Postorder)
Value of T(0) will be some constant say d. (traversing a empty tree will take some constants
time)
T(n) = n(c+d)
T(n) = Θ(n) (Theta of n)
Case 2: Both left and right subtrees have equal number of nodes.
T(n) = 2T(|_n/2_|) + c
This recursive function is in the standard form (T(n) = aT(n/b) + (-)(n) ) for master
method http://en.wikipedia.org/wiki/Master_theorem. If we solve it by master method we
get (-)(n)
Auxiliary Space : If we don’t consider size of stack for function calls then O(1) otherwise
O(n).
Improved By : danielbritten
Source
https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/
2512
Chapter 429
2513
Chapter 429. Two Dimensional Segment Tree | Sub-Matrix Sum
Step 1 : We will first create the segment tree of each strip of y- axis.We repesent the
segment tree here as an array where child node is 2n and 2n+1 where n > 0.
Segment Tree for strip y=1
2514
Chapter 429. Two Dimensional Segment Tree | Sub-Matrix Sum
Step 2: In this step, we create the segment tree for the rectangular matrix where the base
node are the strips of y-axis given above.The task is to merge above segment trees.
Sum Query :
2515
Chapter 429. Two Dimensional Segment Tree | Sub-Matrix Sum
2516
Chapter 429. Two Dimensional Segment Tree | Sub-Matrix Sum
*/
int finalSegment(int low, int high, int pos)
{
if (high == low) {
for (int i = 1; i < 2 * size; i++)
fin_seg[pos][i] = ini_seg[low][i];
}
else {
int mid = (low + high) / 2;
finalSegment(low, mid, 2 * pos);
finalSegment(mid + 1, high, 2 * pos + 1);
for (int i = 1; i < 2 * size; i++)
fin_seg[pos][i] = fin_seg[2 * pos][i] +
fin_seg[2 * pos + 1][i];
}
}
/*
* Return sum of elements in range from index
* x1 to x2 . It uses the final_seg[][] array
* created using finalsegment() function.
* 'pos' is index of current node in
* segment tree fin_seg[][].
*/
int finalQuery(int pos, int start, int end,
int x1, int x2, int node)
{
if (x2 < start || end < x1) {
return 0;
}
if (x1 <= start && end <= x2) {
return fin_seg[node][pos];
}
int mid = (start + end) / 2;
int p1 = finalQuery(2 * pos, start, mid,
x1, x2, node);
int p2 = finalQuery(2 * pos + 1, mid + 1,
end, x1, x2, node);
return (p1 + p2);
}
/*
2517
Chapter 429. Two Dimensional Segment Tree | Sub-Matrix Sum
2518
Chapter 429. Two Dimensional Segment Tree | Sub-Matrix Sum
2519
Chapter 429. Two Dimensional Segment Tree | Sub-Matrix Sum
Output:
Time complexity :
Processing Query : O(logn*logm)
Modification Query: O(2*n*logn*logm)
Space Complexity : O(4*m*n)
Source
https://www.geeksforgeeks.org/two-dimensional-segment-tree-sub-matrix-sum/
2520
Chapter 430
1
/ \
2 3
/ \ / \
4 5 6 7
2521
Chapter 430. Vertical Sum in Binary Tree | Set 2 (Space Optimized)
verticalSumDLL(root)
1) Create a node of doubly linked list node
with value 0. Let the node be llnode.
2) verticalSumDLL(root, llnode)
verticalSumDLL(tnode, llnode)
1) Add current node's data to its vertical line
llnode.data = llnode.data + tnode.data;
2) Recursively process left subtree
// If left child is not empty
if (tnode.left != null)
{
if (llnode.prev == null)
{
llnode.prev = new LLNode(0);
llnode.prev.next = llnode;
}
verticalSumDLLUtil(tnode.left, llnode.prev);
}
3) Recursively process right subtree
if (tnode.right != null)
{
if (llnode.next == null)
{
llnode.next = new LLNode(0);
llnode.next.prev = llnode;
}
verticalSumDLLUtil(tnode.right, llnode.next);
}
C++
2522
Chapter 430. Vertical Sum in Binary Tree | Set 2 (Space Optimized)
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
/// Doubly linked list structure
struct LLNode{
int key;
struct LLNode *prev, *next;
};
/// Function to create new Linked List Node
LLNode* newLLNode(int key)
{
LLNode* temp = new LLNode;
temp->key = key;
temp->prev = temp->next = NULL;
return temp;
}
/// Function that creates Linked list and store
/// vertical sum in it.
void verticalSumDLLUtil(TNode *root, LLNode *sumNode)
{
/// Update sum of current line by adding value
/// of current tree node.
sumNode->key = sumNode->key + root->key;
/// Recursive call to left subtree.
if(root->left)
{
if(sumNode->prev == NULL)
{
sumNode->prev = newLLNode(0);
sumNode->prev->next = sumNode;
}
verticalSumDLLUtil(root->left, sumNode->prev);
}
/// Recursive call to right subtree.
if(root->right)
{
if(sumNode->next == NULL)
{
sumNode->next = newLLNode(0);
sumNode->next->prev = sumNode;
}
verticalSumDLLUtil(root->right, sumNode->next);
2523
Chapter 430. Vertical Sum in Binary Tree | Set 2 (Space Optimized)
}
}
/// Function to print vertical sum of Tree.
/// It uses verticalSumDLLUtil() to calculate sum.
void verticalSumDLL(TNode* root)
{
/// Create Linked list node for
/// line passing through root.
LLNode* sumNode = newLLNode(0);
/// Compute vertical sum of different lines.
verticalSumDLLUtil(root, sumNode);
/// Make doubly linked list pointer point
/// to first node in list.
while(sumNode->prev != NULL){
sumNode = sumNode->prev;
}
/// Print vertical sum of different lines
/// of binary tree.
while(sumNode != NULL){
cout << sumNode->key <<" ";
sumNode = sumNode->next;
}
}
int main()
{
/*
1
/ \
/ \
2 3
/ \ / \
/ \ / \
4 5 6 7
*/
TNode *root = newTNode(1);
root->left = newTNode(2);
root->right = newTNode(3);
root->left->left = newTNode(4);
root->left->right = newTNode(5);
root->right->left = newTNode(6);
root->right->right = newTNode(7);
cout << "Vertical Sums are\n";
2524
Chapter 430. Vertical Sum in Binary Tree | Set 2 (Space Optimized)
verticalSumDLL(root);
return 0;
}
// This code is contributed by <b>Rahul Titare</b>
Java
2525
Chapter 430. Vertical Sum in Binary Tree | Set 2 (Space Optimized)
2526
Chapter 430. Vertical Sum in Binary Tree | Set 2 (Space Optimized)
Output :
This article is contributed by Rahul Titare. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Improved By : nik1996
Source
https://www.geeksforgeeks.org/vertical-sum-in-binary-tree-set-space-optimized/
2527
Chapter 431
1
/ \
2 3
/ \ / \
4 5 6 7
2528
Chapter 431. Vertical Sum in a given Binary Tree | Set 1
recursively calculate HDs. We initially pass the horizontal distance as 0 for root. For left
subtree, we pass the Horizontal Distance as Horizontal distance of root minus 1. For right
subtree, we pass the Horizontal Distance as Horizontal Distance of root plus 1.
Following is Java implementation for the same. HashMap is used to store the vertical sums
for different horizontal distances. Thanks to Nages for suggesting this method.
Java
import java.util.HashMap;
// Class for a tree node
class TreeNode {
// data members
private int key;
private TreeNode left;
private TreeNode right;
// Accessor methods
public int key() { return key; }
public TreeNode left() { return left; }
public TreeNode right() { return right; }
// Constructor
public TreeNode(int key)
{ this.key = key; left = null; right = null; }
// Methods to set left and right subtrees
public void setLeft(TreeNode left) { this.left = left; }
public void setRight(TreeNode right) { this.right = right; }
}
// Class for a Binary Tree
class Tree {
private TreeNode root;
// Constructors
public Tree() { root = null; }
public Tree(TreeNode n) { root = n; }
// Method to be called by the consumer classes
// like Main class
public void VerticalSumMain() { VerticalSum(root); }
// A wrapper over VerticalSumUtil()
private void VerticalSum(TreeNode root) {
2529
Chapter 431. Vertical Sum in a given Binary Tree | Set 1
// base case
if (root == null) { return; }
// Creates an empty hashMap hM
HashMap<Integer, Integer> hM =
new HashMap<Integer, Integer>();
// Calls the VerticalSumUtil() to store the
// vertical sum values in hM
VerticalSumUtil(root, 0, hM);
// Prints the values stored by VerticalSumUtil()
if (hM != null) {
System.out.println(hM.entrySet());
}
}
// Traverses the tree in Inoorder form and builds
// a hashMap hM that contains the vertical sum
private void VerticalSumUtil(TreeNode root, int hD,
HashMap<Integer, Integer> hM) {
// base case
if (root == null) { return; }
// Store the values in hM for left subtree
VerticalSumUtil(root.left(), hD - 1, hM);
// Update vertical sum for hD of this node
int prevSum = (hM.get(hD) == null) ? 0 : hM.get(hD);
hM.put(hD, prevSum + root.key());
// Store the values in hM for right subtree
VerticalSumUtil(root.right(), hD + 1, hM);
}
}
// Driver class to test the verticalSum methods
public class Main {
public static void main(String[] args) {
/* Create following Binary Tree
1
/ \
2 3
/ \ / \
4 5 6 7
2530
Chapter 431. Vertical Sum in a given Binary Tree | Set 1
*/
TreeNode root = new TreeNode(1);
root.setLeft(new TreeNode(2));
root.setRight(new TreeNode(3));
root.left().setLeft(new TreeNode(4));
root.left().setRight(new TreeNode(5));
root.right().setLeft(new TreeNode(6));
root.right().setRight(new TreeNode(7));
Tree t = new Tree(root);
System.out.println("Following are the values of" +
" vertical sums with the positions" +
" of the columns with respect to root ");
t.VerticalSumMain();
}
}
C++
2531
Chapter 431. Vertical Sum in a given Binary Tree | Set 1
2532
Chapter 431. Vertical Sum in a given Binary Tree | Set 1
Source
https://www.geeksforgeeks.org/vertical-sum-in-a-given-binary-tree/
2533
Chapter 432
In this image, the tree contains 6 vertical lines which is the required width of tree.
Examples :
Input :
7
2534
Chapter 432. Vertical width of Binary tree | Set 1
/ \
6 5
/ \ / \
4 3 2 1
Output :
5
Input :
1
/ \
2 3
/ \ / \
4 5 6 7
\ \
8 9
Output :
6
Approach : Take inorder traversal and then take a temporary variable, if we go left then
temp value decreases and if go to right then temp value increases. Assert a condition in
this, if minimum is greater than temp, then minimum = temp and if maximum less then
temp then maximum = temp. At the end, print minimum + maximum which is the vertical
width of the tree.
2535
Chapter 432. Vertical width of Binary tree | Set 1
2536
Chapter 432. Vertical width of Binary tree | Set 1
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/width-binary-tree-set-1/
2537
Chapter 433
Input :
7
/ \
6 5
/ \ / \
4 3 2 1
Output : 5
Input :
1
/ \
2 3
/ \ / \
4 5 6 7
\ \
8 9
Output : 6
2538
Chapter 433. Vertical width of Binary tree | Set 2
In this image, the tree contains 6 vertical lines which is the required width of tree.
Approach : In this Approach, we use the approach for printing vertical View of binary
tree. Store the horizontal distances in a set and return 1 + highest horizontal distance
– lowest horizontal distance. 1 is added to consider horizontal distance 0 as well. While
going left, do hd – 1 and for right do hd + 1. We insert all possible distances in a hash
table and finally return size of the hash table.
2539
Chapter 433. Vertical width of Binary tree | Set 2
int hd)
{
if (!root)
return;
fillSet(root->left, s, hd - 1);
s.insert(hd);
fillSet(root->right, s, hd + 1);
}
int verticalWidth(Node* root)
{
unordered_set<int> s;
// Third parameter is horizontal
// distance
fillSet(root, s, 0);
return s.size();
}
int main()
{
Node* root = NULL;
// Creating the above tree
root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
root->right->right = new Node(7);
root->right->left->right = new Node(8);
root->right->right->right = new Node(9);
cout << verticalWidth(root) << "\n";
return 0;
}
Output:
2540
Chapter 433. Vertical width of Binary tree | Set 2
Source
https://www.geeksforgeeks.org/vertical-width-binary-tree-set-2/
2541
Chapter 434
Ways to color a skewed tree such that parent and child have different colors - GeeksforGeeks
Given a skewed tree (Every node has at most one child) with N nodes and K colors. You
have to assign a color from 1 to K to each node such that parent and child has different
colors. Find the maximum number of ways of coloring the nodes.
Examples –
Input : N = 2, K = 2.
Output :
Let A1 and A2 be the two nodes.
Let A1 is parent of A2.
Colors are Red and Blue.
Case 1: A1 is colored Red
and A2 is colored Blue.
Case 2: A1 is colored Blue
and A2 is colored Red.
No. of ways : 2
Input : N = 3, K = 3.
Output :
A1, A2, A3 are the nodes.
A1 is parent of A2
and A2 is parent of A3.
Let colors be R, B, G.
A1 can choose any three colors
and A2 can choose
2542
Chapter 434. Ways to color a skewed tree such that parent and child have different colors
Note that only the root and children (children, grand children, grand grand children ….
and all) should have different colors. The root of the tree can choose any of the K colors
so K ways. Every other node can choose other K-1 colors other than its parent. So every
node has K-1 choices.
Here, we select the tree as every node as only one child. We can choose any of the K colors
for the root of the tree so K ways. And we are left with K-1 colors for its child. So for every
child we can assign a color other than its parent. Thus, for each of the N-1 nodes we are
left with K-1 colors. Thus the answer is K*(K-1)^(N-1).
We can find the answer by using normal power function which takes O(N) time complexity.
But for better time complexity we use Faster Exponentiation function which takes O(log
N) time complexity.
C++
2543
Chapter 434. Ways to color a skewed tree such that parent and child have different colors
int N = 3, K = 3;
cout << countWays(N, K);
return 0;
}
Java
Python3
2544
Chapter 434. Ways to color a skewed tree such that parent and child have different colors
C#
2545
Chapter 434. Ways to color a skewed tree such that parent and child have different colors
PHP
<?php
// PHP program to count number
// of ways to color a N node
// skewed tree with k colors
// such that parent and children
// have different colors.
// fast_way is recursive
// method to calculate power
function fastPow($N, $K)
{
if ($K == 0)
return 1;
$temp = fastPow($N, $K / 2);
if ($K % 2 == 0)
return $temp * $temp;
else
return $N * $temp * $temp;
}
function countWays($N, $K)
{
return $K * fastPow($K - 1, $N - 1);
}
// Driver Code
$N = 3;
$K = 3;
echo countWays($N, $K);
2546
Chapter 434. Ways to color a skewed tree such that parent and child have different colors
// This code is contributed by ajit
?>
Output :
12
Source
https://www.geeksforgeeks.org/ways-to-color-a-skewed-tree-such-that-parent-and-child-have-different-colors/
2547
Chapter 435
To identify if two trees are identical, we need to traverse both trees simultaneously, and
while traversing we need to compare data and children of the trees.
Algorithm:
sameTree(tree1, tree2)
1. If both trees are empty then return 1.
2. Else If both trees are non -empty
(a) Check data of the root nodes (tree1->data == tree2->data)
(b) Check left subtrees recursively i.e., call sameTree(
tree1->left_subtree, tree2->left_subtree)
(c) Check right subtrees recursively i.e., call sameTree(
tree1->right_subtree, tree2->right_subtree)
(d) If a,b and c are true then return 1.
3 Else return 0 (one is empty and other is not)
C/C++
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
2548
Chapter 435. Write Code to Determine if Two Trees are Identical
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Given two trees, return true if they are
structurally identical */
int identicalTrees(struct node* a, struct node* b)
{
/*1. both empty */
if (a==NULL && b==NULL)
return 1;
/* 2. both non-empty -> compare them */
if (a!=NULL && b!=NULL)
{
return
(
a->data == b->data &&
identicalTrees(a->left, b->left) &&
identicalTrees(a->right, b->right)
);
}
/* 3. one empty, one not -> false */
return 0;
}
/* Driver program to test identicalTrees function*/
int main()
{
struct node *root1 = newNode(1);
struct node *root2 = newNode(1);
root1->left = newNode(2);
2549
Chapter 435. Write Code to Determine if Two Trees are Identical
root1->right = newNode(3);
root1->left->left = newNode(4);
root1->left->right = newNode(5);
root2->left = newNode(2);
root2->right = newNode(3);
root2->left->left = newNode(4);
root2->left->right = newNode(5);
if(identicalTrees(root1, root2))
printf("Both tree are identical.");
else
printf("Trees are not identical.");
getchar();
return 0;
}
Java
2550
Chapter 435. Write Code to Determine if Two Trees are Identical
Python
2551
Chapter 435. Write Code to Determine if Two Trees are Identical
Time Complexity:
Complexity of the identicalTree() will be according to the tree with lesser number of nodes.
Let number of nodes in two trees be m and n then complexity of sameTree() is O(m) where
m < n. Iterative function to check if two trees are identical.
Source
https://www.geeksforgeeks.org/write-c-code-to-determine-if-two-trees-are-identical/
2552
Chapter 436
Example Tree
Note : In Java automatic garbage collection happens, so we can simply make root null to
delete the tree “root = null”;
C
#include<stdio.h>
#include<stdlib.h>
2553
Chapter 436. Write a program to Delete a Tree
2554
Chapter 436. Write a program to Delete a Tree
root = NULL;
printf("\n Tree deleted ");
return 0;
}
Java
2555
Chapter 436. Write a program to Delete a Tree
/* Print all root-to-leaf paths of the input tree */
tree.deleteTree(tree.root);
tree.root = null;
System.out.println("Tree deleted");
}
}
Output:
Deleting node: 4
Deleting node: 5
Deleting node: 2
Deleting node: 3
Deleting node: 1
Tree deleted
The above deleteTree() function deletes the tree, but doesn’t change root to NULL
which may cause problems if the user of deleteTree() doesn’t change root to NULL
and tires to access values using root pointer. We can modify the deleteTree() function
to take reference to the root node so that this problem doesn’t occur. See the following code.
#include<stdio.h>
#include<stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
2556
Chapter 436. Write a program to Delete a Tree
node->right = NULL;
return(node);
}
/* This function is same as deleteTree() in the previous program */
void _deleteTree(struct node* node)
{
if (node == NULL) return;
/* first delete both subtrees */
_deleteTree(node->left);
_deleteTree(node->right);
/* then delete the node */
printf("\n Deleting node: %d", node->data);
free(node);
}
/* Deletes a tree and sets the root as NULL */
void deleteTree(struct node** node_ref)
{
_deleteTree(*node_ref);
*node_ref = NULL;
}
/* Driver program to test deleteTree function*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
// Note that we pass the address of root here
deleteTree(&root);
printf("\n Tree deleted ");
getchar();
return 0;
}
Java
2557
Chapter 436. Write a program to Delete a Tree
class Node
{
int data;
Node left, right;
Node(int d)
{
data = d;
left = right = null;
}
}
class BinaryTree
{
static Node root;
/* This function is same as deleteTree() in the previous program */
void deleteTree(Node node)
{
// In Java automatic garbage collection
// happens, so we can simply make root
// null to delete the tree
root = null;
}
/* Wrapper function that deletes the tree and
sets root node as null */
void deleteTreeRef(Node nodeRef)
{
deleteTree(nodeRef);
nodeRef=null;
}
/* Driver program to test deleteTree function */
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
/* Note that we pass root node here */
tree.deleteTreeRef(root);
2558
Chapter 436. Write a program to Delete a Tree
System.out.println("Tree deleted");
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Deleting node: 4
Deleting node: 5
Deleting node: 2
Deleting node: 3
Deleting node: 1
Tree deleted
Source
https://www.geeksforgeeks.org/write-a-c-program-to-delete-a-tree/
2559
Chapter 437
Example Tree
Recursively calculate height of left and right subtrees of a node and assign height to the
node as max of the heights of two children plus 1. See below pseudo code and program for
details.
Algorithm:
maxDepth()
1. If tree is empty then return 0
2. Else
2560
Chapter 437. Write a Program to Find the Maximum Depth or Height of a Tree
See the below diagram for more clarity about execution of the recursive function
maxDepth() for above example tree.
Implementation:
C
#include<stdio.h>
#include<stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
2561
Chapter 437. Write a Program to Find the Maximum Depth or Height of a Tree
/* Compute the "maxDepth" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int maxDepth(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the depth of each subtree */
int lDepth = maxDepth(node->left);
int rDepth = maxDepth(node->right);
/* use the larger one */
if (lDepth > rDepth)
return(lDepth+1);
else return(rDepth+1);
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Hight of tree is %d", maxDepth(root));
getchar();
return 0;
}
2562
Chapter 437. Write a Program to Find the Maximum Depth or Height of a Tree
Java
2563
Chapter 437. Write a Program to Find the Maximum Depth or Height of a Tree
Python
2564
Chapter 437. Write a Program to Find the Maximum Depth or Height of a Tree
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "Height of tree is %d" %(maxDepth(root))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Time Complexity: O(n) (Please see our post Tree Traversalfor details)
References:
http://cslibrary.stanford.edu/110/BinaryTrees.html
Improved By : coduitachi
Source
https://www.geeksforgeeks.org/write-a-c-program-to-find-the-maximum-depth-or-height-of-a-tree/
2565
Chapter 438
Example Tree
Size() function recursively calculates the size of a tree. It works as follows:
Size of a tree = Size of left subtree + 1 + Size of right subtree.
Algorithm:
size(tree)
1. If tree is empty then return 0
2. Else
(a) Get the size of left subtree recursively i.e., call
size( tree->left-subtree)
(a) Get the size of right subtree recursively i.e., call
size( tree->right-subtree)
2566
Chapter 438. Write a program to Calculate Size of a tree | Recursion
#include <stdio.h>
#include <stdlib.h>
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Computes the number of nodes in a tree. */
int size(struct node* node)
{
if (node==NULL)
return 0;
else
return(size(node->left) + 1 + size(node->right));
}
/* Driver program to test size function*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
2567
Chapter 438. Write a program to Calculate Size of a tree | Recursion
root->left->right = newNode(5);
printf("Size of the tree is %d", size(root));
getchar();
return 0;
}
Java
2568
Chapter 438. Write a program to Calculate Size of a tree | Recursion
Python
Output:
2569
Chapter 438. Write a program to Calculate Size of a tree | Recursion
Time & Space Complexities: Since this program is similar to traversal of tree, time and
space complexities will be same as Tree traversal (Please see our Tree Traversal post for
details)
Source
https://www.geeksforgeeks.org/write-a-c-program-to-calculate-size-of-a-tree/
2570
Chapter 439
XOR of numbers that appeared even number of times in given Range - GeeksforGeeks
Given an array of numbers of size N and Q queries. Each query or a range can be represented
by L (LeftIndex) and R(RightIndex). Find the XOR-sum of the numbers that appeared even
number of times in the given range.
Prerequisite : Queries for number of distinct numbers in given range. | Segment Tree for
range query
Examples :
Input : arr[] = { 1, 2, 1, 3, 3, 2, 3 }
Q = 5
L = 3, R = 6
L = 3, R = 4
L = 0, R = 2
L = 0, R = 6
L = 0, R = 4
Output : 0
3
1
3
2
2571
Chapter 439. XOR of numbers that appeared even number of times in given Range
2572
Chapter 439. XOR of numbers that appeared even number of times in given Range
2573
Chapter 439. XOR of numbers that appeared even number of times in given Range
}
// Constructs and returns a Binary Indexed
// Tree for given array of size N.
int* constructBITree(int arr[], int N)
{
// Create and initialize BITree[] as 0
int* BIT = new int[N + 1];
for (int i = 1; i <= N; i++)
BIT[i] = 0;
return BIT;
}
// Function to answer the Queries
void answeringQueries(int arr[], int N,
que queries[], int Q, int BIT[])
{
// Creating an array to calculate
// prefix XOR sums
int* prefixXOR = new int[N + 1];
// map for coordinate compression
// as numbers can be very large but we
// have limited space
map<int, int> mp;
for (int i = 0; i < N; i++) {
// If A[i] has not appeared yet
if (!mp[arr[i]])
mp[arr[i]] = i;
// calculate prefixXOR sums
if (i == 0)
prefixXOR[i] = arr[i];
else
prefixXOR[i] =
prefixXOR[i - 1] ^ arr[i];
}
// Creating an array to store the
// last occurence of arr[i]
int lastOcc[1000001];
memset(lastOcc, -1, sizeof(lastOcc));
// sort the queries according to comparator
2574
Chapter 439. XOR of numbers that appeared even number of times in given Range
2575
Chapter 439. XOR of numbers that appeared even number of times in given Range
{
int arr[] = { 1, 2, 1, 3, 3, 2, 3 };
int N = sizeof(arr) / sizeof(arr[0]);
int* BIT = constructBITree(arr, N);
// structure of array for queries
que queries[5];
// Intializing values (L, R, idx) to queries
queries[0].L = 3;
queries[0].R = 6, queries[0].idx = 0;
queries[1].L = 3;
queries[1].R = 4, queries[1].idx = 1;
queries[2].L = 0;
queries[2].R = 2, queries[2].idx = 2;
queries[3].L = 0;
queries[3].R = 6, queries[3].idx = 3;
queries[4].L = 0;
queries[4].R = 4, queries[4].idx = 4;
int Q = sizeof(queries) / sizeof(queries[0]);
// answer Queries
answeringQueries(arr, N, queries, Q, BIT);
return 0;
}
Output:
0
3
1
3
2
Time Complexity: O(Q * Log(N)), where N is the size of array, Q is the total number of
queries.
Source
https://www.geeksforgeeks.org/xor-numbers-appeared-even-number-times-given-range/
2576
Chapter 440
This problem can be solved using two stacks. Assume the two stacks are current: cur-
rentlevel and nextlevel. We would also need a variable to keep track of the current level
order(whether it is left to right or right to left). We pop from the currentlevel stack and print
the nodes value. Whenever the current level order is from left to right, push the nodes left
child, then its right child to the stack nextlevel. Since a stack is a LIFO(Last-In-First_out)
structure, next time when nodes are popped off nextlevel, it will be in the reverse order. On
the other hand, when the current level order is from right to left, we would push the nodes
right child first, then its left child. Finally, do-not forget to swap those two stacks at the
end of each level(i.e., when current level is empty)
Below is the implementation of the above approach:
C++
2577
Chapter 440. ZigZag Tree Traversal
#include <stack>
using namespace std;
// Binary Tree node
struct Node {
int data;
struct Node *left, *right;
};
// function to print the zigzag traversal
void zizagtraversal(struct Node* root)
{
// if null then return
if (!root)
return;
// declare two stacks
stack<struct Node*> currentlevel;
stack<struct Node*> nextlevel;
// push the root
currentlevel.push(root);
// check if stack is empty
bool lefttoright = true;
while (!currentlevel.empty()) {
// pop out of stack
struct Node* temp = currentlevel.top();
currentlevel.pop();
// if not null
if (temp) {
// print the data in it
cout << temp->data << " ";
// store data according to current
// order.
if (lefttoright) {
if (temp->left)
nextlevel.push(temp->left);
if (temp->right)
nextlevel.push(temp->right);
}
else {
if (temp->right)
nextlevel.push(temp->right);
2578
Chapter 440. ZigZag Tree Traversal
if (temp->left)
nextlevel.push(temp->left);
}
}
if (currentlevel.empty()) {
lefttoright = !lefttoright;
swap(currentlevel, nextlevel);
}
}
}
// A utility function to create a new node
struct Node* newNode(int data)
{
struct Node* node = new struct Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// driver program to test the above function
int main()
{
// create tree
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
cout << "ZigZag Order traversal of binary tree is \n";
zizagtraversal(root);
return 0;
}
Java
2579
Chapter 440. ZigZag Tree Traversal
int data;
Node leftChild;
Node rightChild;
Node(int data)
{
this.data = data;
}
}
class BinaryTree {
Node rootNode;
// function to print the
// zigzag traversal
void printZigZagTraversal() {
// if null then return
if (rootNode == null) {
return;
}
// declare two stacks
Stack<Node> currentLevel = new Stack<>();
Stack<Node> nextLevel = new Stack<>();
// push the root
currentLevel.push(rootNode);
boolean leftToRight = true;
// check if stack is empty
while (!currentLevel.isEmpty()) {
// pop out of stack
Node node = currentLevel.pop();
// print the data in it
System.out.print(node.data + " ");
// store data according to current
// order.
if (leftToRight) {
if (node.leftChild != null) {
nextLevel.push(node.leftChild);
}
if (node.rightChild != null) {
nextLevel.push(node.rightChild);
}
2580
Chapter 440. ZigZag Tree Traversal
}
else {
if (node.rightChild != null) {
nextLevel.push(node.rightChild);
}
if (node.leftChild != null) {
nextLevel.push(node.leftChild);
}
}
if (currentLevel.isEmpty()) {
leftToRight = !leftToRight;
Stack<Node> temp = currentLevel;
currentLevel = nextLevel;
nextLevel = temp;
}
}
}
}
public class zigZagTreeTraversal {
// driver program to test the above function
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.rootNode = new Node(1);
tree.rootNode.leftChild = new Node(2);
tree.rootNode.rightChild = new Node(3);
tree.rootNode.leftChild.leftChild = new Node(7);
tree.rootNode.leftChild.rightChild = new Node(6);
tree.rootNode.rightChild.leftChild = new Node(5);
tree.rootNode.rightChild.rightChild = new Node(4);
System.out.println("ZigZag Order traversal of binary tree is");
tree.printZigZagTraversal();
}
}
// This Code is contributed by Harikrishnan Rajan.
Python3
2581
Chapter 440. ZigZag Tree Traversal
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = self.right = None
# function to print zigzag traversal of
# binary tree
def zizagtraversal(root):
# Base Case
if root is None:
return
# Create two stacks to store current
# and next level
currentLevel = []
nextLevel = []
# if ltr is true push nodes from
# left to right otherwise from
# right to left
ltr = True
# append root to currentlevel stack
currentLevel.append(root)
# Check if stack is empty
while len(currentLevel) > 0:
# pop from stack
temp = currentLevel.pop(-1)
# print the data
print(temp.data, " ", end="")
if ltr:
# if ltr is true push left
# before right
if temp.left:
nextLevel.append(temp.left)
if temp.right:
nextLevel.append(temp.right)
else:
# else push right before left
if temp.right:
nextLevel.append(temp.right)
if temp.left:
nextLevel.append(temp.left)
2582
Chapter 440. ZigZag Tree Traversal
if len(currentLevel) == 0:
# reverse ltr to push node in
# opposite order
ltr = not ltr
# swapping of stacks
currentLevel, nextLevel = nextLevel, currentLevel
# Driver program to check above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
print("Zigzag Order traversal of binary tree is")
zizagtraversal(root)
# This code is contributed by Shweta Singh
Output:
Source
https://www.geeksforgeeks.org/zigzag-tree-traversal/
2583
Chapter 441
The image above is the Calkin-Wilf Tree where all the rational numbers are listed. The
children of a node a/b is calculated as a/(a+b) and (a+b)/b.
The task is to find the nth rational number in breadth first traversal of this tree.
Examples:
Input : 13
Output : [5, 3]
2584
Chapter 441. nth Rational number in Calkin-Wilf sequence
Input : 5
Output : [3, 2]
Explanation: This tree is a Perfect Binary Search tree and we need floor(log(n)) steps to
compute nth rational number. The concept is similar to searching in a binary search tree.
Given n we keep dividing it by 2 until we get 0. We return fraction at each stage in the
following manner:-
if n%2 == 0
update frac[1]+=frac[0]
else
update frac[0]+=frac[1]
Below is the program to find the nth number in Calkin Wilf sequence:
C++
2585
Chapter 441. nth Rational number in Calkin-Wilf sequence
nthRational(n);
cout << "[" << frac[0] << ","
<< frac[1] << "]" << endl;
return 0;
}
// This code is contributed
// by Harshit Saini
Java
Python3
2586
Chapter 441. nth Rational number in Calkin-Wilf sequence
frac = [0, 1]
# returns 1x2 int array
# which contains the nth
# rational number
def nthRational(n):
if n > 0:
nthRational(int(n / 2))
# ~n&1 is equivalent to
# !n%2?1:0 and n&1 is
# equivalent to n%2
frac[~n & 1] += frac[n & 1]
return frac
# Driver code
if __name__ == "__main__":
n = 13 # testing for n=13
# converting array
# to string format
print(nthRational(n))
# This code is contributed
# by Harshit Saini
Output:
[5, 3]
Explanation:
For n = 13,
2587
Chapter 441. nth Rational number in Calkin-Wilf sequence
Source
https://www.geeksforgeeks.org/nth-rational-number-in-calkin-wilf-sequence/
2588