Created
April 10, 2017 15:20
-
-
Save jluismm2311/b4fa7863d72eaee51383a16ded5090d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class TreeNode { | |
TreeNode left; | |
TreeNode right; | |
public static boolean isPerfect(TreeNode root) { | |
if(root == null){ | |
return true; | |
} | |
Queue queue = new LinkedList<TreeNode>(); | |
queue.add(root); | |
int treeSize = 0; | |
while (!queue.isEmpty()){ | |
TreeNode leafIterative = (TreeNode)queue.remove(); | |
treeSize++; | |
if(leafIterative.left != null){ | |
queue.add(leafIterative.left); | |
} | |
if(leafIterative.right != null){ | |
queue.add(leafIterative.right); | |
} | |
} | |
return isPerfect(treeSize); | |
} | |
static boolean isPerfect(int size){ | |
boolean result = false; | |
int index = 0; | |
double expectedSize = 0; | |
while(!result && expectedSize< size){ | |
expectedSize += Math.pow(2,index); | |
if((double)size == expectedSize){ | |
result = true; | |
} | |
index++; | |
} | |
return result; | |
} | |
static TreeNode leaf() { | |
return new TreeNode(); | |
} | |
static TreeNode join(TreeNode left, TreeNode right) { | |
return new TreeNode().withChildren(left, right); | |
} | |
TreeNode withLeft(TreeNode left) { | |
this.left = left; | |
return this; | |
} | |
TreeNode withRight(TreeNode right) { | |
this.right = right; | |
return this; | |
} | |
TreeNode withChildren(TreeNode left, TreeNode right) { | |
this.left = left; | |
this.right = right; | |
return this; | |
} | |
TreeNode withLeftLeaf() { | |
return withLeft(leaf()); | |
} | |
TreeNode withRightLeaf() { | |
return withRight(leaf()); | |
} | |
TreeNode withLeaves() { | |
return withChildren(leaf(), leaf()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment