step1: include root node,checking that root node is not leaf node.
step2: move towars left part of tree,if node has left then that will be our answer,and if node does not have left then right node will be our answer.
step3: Do preOrder traversal (or any traversal- pre/In/post)and find leaf node.
step4:move towards right part of tree,if node has right then that will be our answer,and if node does not have right then left node will be our answer.
import java.util.*;
public class Solution
{
public static List<Integer> traverseBoundary(TreeNode root)
{
// Write your code here.
List<Integer> list=new ArrayList<Integer>();
//step 1: include root (if root is not leaf)
if(! isLeaf(root) )
{
list.add(root.data);
}
//step 2: include left boundary (movement in left part of root)
leftBoundary(root,list);
//step 3: include leaf (pre order traversal on entire tree)
leafNode(root,list);
//step 4: include right boundary(movement in right part of root)
rightBoundary(root,list);
return list;
}
public static void leftBoundary(TreeNode node,List list)
{
TreeNode leftNode=node.left;
while(leftNode!=null)
{
//step A: is this node is leaf
if(isLeaf(leftNode))
{
break;
}
// not leaf,include in left boundary
list.add(leftNode.data);
//updating while condition
if(leftNode.left!=null) //agar left exist---> include in leftBoundary
leftNode=leftNode.left;
else //agar left not exist,only then right child will be in leftBoundary
leftNode=leftNode.right;
}
}
public static void rightBoundary(TreeNode node,List list)
{
TreeNode rightNode=node.right;
Stack<Integer> st=new Stack<>();
while(rightNode!=null)
{
//step A: is this node is leaf
if(isLeaf(rightNode))
{
break;
}
// not leaf,include in right boundary
// list.add(rightNode.data);
// storing data in stack bcz we need rightboundary data in reverse order
st.push(rightNode.data);
//updating while condition
if(rightNode.right!=null) //agar left exist---> include in leftBoundary
rightNode=rightNode.right;
else //agar left not exist,only then right child will be in leftBoundary
rightNode=rightNode.left;
}
// storing data in list from stack
while(! st.isEmpty() ) //while(st.size()>0)
{
list.add(st.pop());
}
}
public static void leafNode(TreeNode node,List list)
{
if(node==null)
return;
if(isLeaf(node))
list.add(node.data);
leafNode(node.left,list);
leafNode(node.right,list);
}
public static boolean isLeaf(TreeNode node)
{
return (node.left==null && node.right==null);
}
}