Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to print all ancestors of a node in a given binary tree
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.io.*;
- import java.lang.reflect.Array;
- import java.util.*;
- import static java.lang.Integer.max;
- // node class
- class node{
- int data;
- node left;
- node right;
- // function that returns a pointer to new node
- public node(int element){
- this.data = element;
- this.left = null;
- this.right = null;
- }
- };
- public class BinaryTree {
- // function to print all the ancestors of a node
- static boolean ancestors(node root, int target){
- // if the current node is null then return false
- if(root == null){
- return false;
- }
- // if the current node is our target node then we return true
- if(root.data == target){
- return true;
- }
- // here we recursively check if the current node if the ancestor of the target node then we need to print it
- // the target node might lie in the left or the right subtree
- // thus we take or of the the returned boolean values
- if(ancestors(root.left, target) || ancestors(root.right, target)){
- System.out.print(root.data + " ");
- return true;
- }
- return false;
- }
- public static void main(String arg[]) {
- node head = new node(1);
- head.left = new node(2);
- head.right = new node(3);
- head.left.left = new node(4);
- head.left.right = new node(5);
- head.right.right = new node(6);
- head.left.left.right = new node(7);
- head.right.right.left = new node(8);
- head.left.left.right.left = new node(9);
- head.left.left.right.left.left = new node(10);
- head.right.right.left.right = new node(11);
- System.out.println("All ancestors of node 10 are : ");
- ancestors(head, 10);
- System.out.println("\nAll ancestors of node 5 are : ");
- ancestors(head, 5);
- System.out.println("\nAll ancestors of node 8 are : ");
- ancestors(head, 8);
- }
- }
Add Comment
Please, Sign In to add comment