how to print leaf nodes in a binary search tree

The logic here is simple. Recursively go through left and then right elements, when the base condition is met (i.e, when r==null), add a check to see if the node’s left and right wings are null and if they are null print the value of the node.

Input binary search tree:
BST_LeafNodes

    // print leaf nodes
    public void leafNodes(BinaryNode r) {
    	if(r!= null) {
    		leafNodes(r.left);
    		leafNodes(r.right);

    		if(r.left == null && r.right == null) {
    			System.out.println(r.element);
    		}
    	}
    }

Note: This logic is same is recursive post order traversal, but instead of just printing the node value after left&right traversals we check to see if left&right children are null and then print the node value.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: