Wednesday, March 2, 2011

Print Ancestors of given Node in a Binary Tree

Question : Print Ancestors of given Node in a Binary Tree ?
Ans : 

private static boolean printAncestors(Node root, int target) {
if(root == null)
return false;
else if(root.val == target){
return true;
}else if(printAncestors(root.left,target) || (printAncestors(root.right,target))){
System.out.println("Ancestor : "+root.val);
return true;
}else{
return false;
}
}
Question : Print Level Order traversal of Given BST ?


Ans: private static void printLevelOrderBST(Node node) {
if(queue.isEmpty()){
queue.add(node);
}
while(!queue.isEmpty()) {
Node myNode = queue.remove();
System.out.println(" Value : "+myNode.val);
if(myNode.left != null ){
queue.add(myNode.left);
}
if(myNode.right != null){
queue.add(node.right);
}
}
}

No comments:

AWS certification question

AWS AWS Hi! this is for questions related to AWS questions. EC2 instances EC2 storage types cold HDD : 1. Defines performance in terms...