Created
June 22, 2012 17:55
-
-
Save jlbelmonte/2974237 to your computer and use it in GitHub Desktop.
n-ary tree univalence
This file contains hidden or 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.ArrayList; | |
import java.util.List; | |
/* root with three children | |
O | |
/ | \ | |
O O O | |
/ / \ \ | \ | |
O O O O O O | |
/ | |
O | |
*/ | |
public class Node { | |
int value; | |
List<Node> children; | |
public Node(int val){ | |
value = val; | |
children = new ArrayList<Node>(); | |
} | |
static boolean isUnival(Node tree, Counter counter){ | |
if (tree == null) return false; | |
boolean totalUnivalence = true; | |
boolean localUnivalence = true; | |
if (tree.children.isEmpty()){ | |
return true; | |
} | |
for ( Node child : tree.children) { | |
boolean uniVal = isUnival(child, counter); | |
if (uniVal) counter.add(1); | |
totalUnivalence = totalUnivalence && uniVal ; | |
if (child.value != tree.value) { | |
localUnivalence = false; | |
} | |
} | |
return totalUnivalence && localUnivalence; | |
} | |
public Counter getCounter() { | |
return new Counter(); | |
} | |
class Counter { | |
int subtrees; | |
public Counter() { | |
subtrees = 0; | |
} | |
public void add(int val) { | |
subtrees+=val; | |
} | |
} | |
public static void main(String[] args) { | |
Node treeRoot = new Node(7); | |
treeRoot.children.add(new Node(7)); | |
Node firstChild = treeRoot.children.get(0); | |
firstChild.children.add(new Node(7)); | |
firstChild.children.add(new Node(7)); | |
firstChild.children.add(new Node(7)); | |
firstChild.children.add(new Node(7)); | |
treeRoot.children.add(new Node(7)); | |
treeRoot.children.add(new Node(7)); | |
Node thirdChild = treeRoot.children.get(2); | |
thirdChild.children.add(new Node(7)); | |
thirdChild.children.add(new Node(7)); | |
thirdChild.children.get(0).children.add(new Node(7)); | |
Counter counter = treeRoot.getCounter(); | |
System.out.println(isUnival(firstChild, counter)); | |
System.out.println(counter.subtrees); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment