booleanisSibling(Node node,Node a,Node b){ // Base case if (node ==null) returnfalse; return ((node.left== a &&node.right== b) || (node.left== b &&node.right== a) ||isSibling(node.left, a, b)||isSibling(node.right, a, b)); }
Construct Binary Tree from given Parent Array
/*Input: parent[] = {1, 5, 5, 2, 2, -1, 3}Output: root of below tree 5 / \ 1 2 / / \ 0 3 4 / 6 */// Creates a node with key as 'i'. If i is root, then it changes // root. If parent of i is not created, then it creates parent first voidcreateNode(int parent[],int i,Node created[]){ // If this node is already created if (created[i] !=null) return; // Create a new node and set created[i] created[i] =newNode(i); // If 'i' is root, change root pointer and return if (parent[i] ==-1) { root = created[i]; return; } // If parent is not created, then create parent first if (created[parent[i]] ==null) createNode(parent, parent[i], created); // Find parent pointer Node p = created[parent[i]]; // If this is first child of parent if (p.left==null) p.left= created[i]; else// If second child p.right= created[i]; } /* Creates tree from parent[0..n-1] and returns root of the created tree */NodecreateTree(int parent[],int n){ // Create an array created[] to keep track // of created nodes, initialize all entries // as NULL Node[] created =newNode[n]; for (int i =0; i < n; i++) created[i] =null; for (int i =0; i < n; i++) createNode(parent, i, created); return root; }
Find Level
intlevel(Node node,Node ptr,int lev){ // base cases if (node ==null) return0; if (node == ptr) return lev; // Return level if Node is present in left subtree int l =level(node.left, ptr, lev +1); if (l !=0) return l; // Else search in right subtree returnlevel(node.right, ptr, lev +1); }
// A utility function that prints all nodes on the // path from root to target_leaf booleanprintPath(Node node,Node target_leaf){ // base case if (node ==null) returnfalse; // return true if this node is the target_leaf or // target leaf is present in one of its descendants if (node == target_leaf ||printPath(node.left, target_leaf)||printPath(node.right, target_leaf)) { System.out.print(node.data+" "); returntrue; } returnfalse; }