<P> The above destructive procedural variant modifies the tree in place . It uses only constant heap space (and the iterative version uses constant stack space as well), but the prior version of the tree is lost . Alternatively, as in the following Python example, we can reconstruct all ancestors of the inserted node; any reference to the original tree root remains valid, making the tree a persistent data structure: </P> <P> The part that is rebuilt uses O (log n) space in the average case and O (n) in the worst case . </P> <P> In either version, this operation requires time proportional to the height of the tree in the worst case, which is O (log n) time in the average case over all trees, but O (n) time in the worst case . </P> <P> Another way to explain insertion is that in order to insert a new node in the tree, its key is first compared with that of the root . If its key is less than the root's, it is then compared with the key of the root's left child . If its key is greater, it is compared with the root's right child . This process continues, until the new node is compared with a leaf node, and then it is added as this node's right or left child, depending on its key: if the key is less than the leaf's key, then it is inserted as the leaf's left child, otherwise as the leaf's right child . </P>

What is binary search tree in data structure with example