Check if two BSTs contain same set of elements | BST Node ; Utility function to create new Node ; function to insert elements of the tree to map m ; function to check if the two BSTs contain same set of elements ; Base cases ; Create two vectors and store inorder traversals of both BSTs in them . ; Return true if both vectors are identical ; First BST ; Second BST ; check if two BSTs have same set of elements
class Node { constructor ( ) { this . data = 0 ; this . prev = null ; this . next = null ; } } function newNode ( val ) { var temp = new Node ( ) ; temp . data = val ; temp . left = temp . right = null ; return temp ; } function storeInorder ( root , v ) { if ( root == null ) return ; storeInorder ( root . left , v ) ; v . push ( root . data ) ; storeInorder ( root . right , v ) ; } function checkBSTs ( root1 , root2 ) { if ( root1 != null && root2 != null ) return true ; if ( ( root1 == null && root2 != null ) || ( root1 != null && root2 == null ) ) return false ; var v1 = [ ] ; var v2 = [ ] ; storeInorder ( root1 , v1 ) ; storeInorder ( root2 , v2 ) ; return ( v1 == v2 ) ; } var root1 = newNode ( 15 ) ; root1 . left = newNode ( 10 ) ; root1 . right = newNode ( 20 ) ; root1 . left . left = newNode ( 5 ) ; root1 . left . right = newNode ( 12 ) ; root1 . right . right = newNode ( 25 ) ; var root2 = newNode ( 15 ) ; root2 . left = newNode ( 12 ) ; root2 . right = newNode ( 20 ) ; root2 . left . left = newNode ( 5 ) ; root2 . left . left . right = newNode ( 10 ) ; root2 . right . right = newNode ( 25 ) ; if ( checkBSTs ( root1 , root2 ) ) document . write ( " " ) ; else document . write ( " " ) ;