Remove all leaf nodes from the binary search tree | JavaScript program to delete leaf Node from binary search tree . ; Create a newNode in binary search tree . ; Insert a Node in binary search tree . ; Function for inorder traversal in a BST . ; Delete leaf nodes from binary search tree . ; Else recursively delete in left and right subtrees . ; Driver code
class Node { constructor ( ) { this . data = 0 ; this . left = null ; this . right = null ; } } function newNode ( data ) { var temp = new Node ( ) ; temp . data = data ; temp . left = null ; temp . right = null ; return temp ; } function insert ( root , data ) { if ( root == null ) return newNode ( data ) ; if ( data < root . data ) root . left = insert ( root . left , data ) ; else if ( data > root . data ) root . right = insert ( root . right , data ) ; return root ; } function inorder ( root ) { if ( root != null ) { inorder ( root . left ) ; document . write ( root . data + " " ) ; inorder ( root . right ) ; } } function leafDelete ( root ) { if ( root == null ) { return null ; } if ( root . left == null && root . right == null ) { return null ; } root . left = leafDelete ( root . left ) ; root . right = leafDelete ( root . right ) ; return root ; } var root = null ; root = insert ( root , 20 ) ; insert ( root , 10 ) ; insert ( root , 5 ) ; insert ( root , 15 ) ; insert ( root , 30 ) ; insert ( root , 25 ) ; insert ( root , 35 ) ; document . write ( " " ) ; inorder ( root ) ; document . write ( " " ) ; leafDelete ( root ) ; document . write ( " " ) ; inorder ( root ) ;