how to print leaf nodes in a binary search tree
November 30, 2012 Leave a comment
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.
// 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.
Recent Comments