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);
}
}
}
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:
Post a Comment