Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.google.challenges;
- import java.util.Stack;
- public class Answer {
- static class BinTree {
- int total;
- int[] nodes;
- Stack<Integer> values = new Stack();
- BinTree(int x) {
- total = (int) Math.pow(2, x) - 1;
- nodes = new int[total];
- //Populate Nodes List
- for (int i = 0, j = total; i < total; i++, j--) {
- nodes[i] = -2;
- values.add(j);
- }
- postOrder(0);
- }
- int eval(int i) {
- if ( i == -1)
- {
- return -1;
- }
- if (i > total-1)
- {
- return -1;
- }
- else
- {
- return nodes[i];
- }
- }
- boolean hasChild(int i) {
- int l = Lchild(i);
- int r = Rchild(i);
- if (l > total - 1 && r > total - 1) {
- return false;
- }
- else
- {
- return true;
- }
- }
- void populateNode(int i){
- int v = values.pop();
- nodes[i] = v;
- }
- void postOrder(int i){
- if (!hasChild(i))
- {
- populateNode(i);
- }
- else
- {
- postOrder(Lchild(i));
- postOrder(Rchild(i));
- populateNode(i);
- }
- }
- int Lchild(int i) {
- return(i*2)+1;
- }
- int Rchild(int i){
- return(i+1)*2;
- }
- }
- public static int parentIndex(int i) {
- int p =(i-1)/2;
- if(i == 0)
- {
- return -1;
- }
- else{
- return p;
- }
- }
- public static int find(int[]array, int x){
- for(int i = 0; i<array.length; i++)
- {
- if (array[i] == x)
- {
- return i;
- }
- }
- return -1;
- }
- public static int[] answer(int h, int[] q) {
- BinTree tree = new BinTree(h);
- int rootVal = tree.nodes[0];
- int[] output = new int[q.length];
- int[] temp = new int[q.length];
- for (int i =0; i < q.length; i++)
- {
- temp[i] = parentIndex(find(tree.nodes, q[i]));
- }
- for (int i =0; i < q.length; i++)
- {
- output[i] = tree.eval(temp[i]);
- }
- delete tree;
- return output;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement