educative.io

Educative

Trees-Print Tree Perimeter

public static void printLeftPerimeter(BinaryTreeNode root, StringBuffer result) 
{ 
if (root == null) {
  return; 
}
if (root.left != null) { 
  // System.out.print(root.data + " "); 
  result.append(String.valueOf(root.data) + " ");
  printLeftPerimeter(root.left, result); 
} 
else if (root.right != null) { 
  //System.out.print(root.data + " ");
  result.append(String.valueOf(root.data) + " ");
  printLeftPerimeter(root.right, result); 
} 
 } 

why are we traversing right node as well,when we have to show only left node
can we replace code as below?

    public static void traverseLeft(Node root){
	
	if(root==null)return;
	if(root.left==null && root.right==null)return;
	else{
		System.out.print(root.data+" ,");
		traverseLeft(root.left);
	}
}

Hi there!

This is Hamza from Educative.

You’ve raised a very useful point about the extra if condition checking the right pointer. For the most part, if we remove the extra condition, our code will work on most scenarios. However, there is one condition that might not work if we remove the additional check.

If the last left node of a tree happens to have no left child but does have a right child (which will be a leaf node and should be considered when finding the tree perimeter), then that right node will be ignored if we went ahead and removed the check. If you think there is a better alternative to make the code seem more readable, please do keep sharing your suggestions, and we will proceed with making any necessary changes to the lesson.

We hope Educative has inspired to further your learning.

Best Regards,
Hamza | Developer Advocate

1 Like

I think the case If the last left node of a tree happens to have no left child but does have a right child (which will be a leaf node and should be considered when finding the tree perimeter)
can be handle in leaf node traversal, as below

  public static void traverseboundryLast(Node root){
	
	if(root==null)return;
	if(root.left==null && root.right==null)System.out.print(root.data+" ,");
	else{
		
		traverseboundryLast(root.left);
		traverseboundryLast(root.right);
	}
}

As my tree is given below and getting correct leaf node from above logic.
OUTPUT:15 ,70 ,400 as we expected.
please correct me If I am wrong.

Your approach does seem like it should handle most edge cases. But there is still a possibility of it failing for some cases. For example, please try running your code on the following tree:

    arr.add(35);
    arr.add(25);
    arr.add(30);
    arr.add(28);
    arr.add(32);
    arr.add(40);    
    arr.add(39);
    arr.add(45);
    arr.add(42);
    arr.add(50);

Because the extra if conditions in the left and right subtree traversal functions will be removed, the solution won’t work on a zig-zag like tree.