Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- For your reference:
- class BinaryTreeNode {
- Integer value;
- BinaryTreeNode left;
- BinaryTreeNode right;
- BinaryTreeNode(Integer value) {
- this.value = value;
- this.left = null;
- this.right = null;
- }
- }
- */
- private static int count = 0;
- static Integer find_single_value_trees(BinaryTreeNode root) {
- if (root == null) {
- return 0;
- }
- isUnival(root);
- return count;
- }
- // return true is the subtree starting from note is unival
- static boolean isUnival(BinaryTreeNode node) {
- if (node.left == null && node.right == null) {
- count++;
- return true;
- }
- boolean unival = true;
- if (node.left != null) {
- if (!isUnival(node.left)) { // make sure this is called if node.left is not null
- unival = false;
- }
- if (!node.value.equals(node.left.value)) {
- unival = false;
- }
- }
- if (node.right != null) {
- if (!isUnival(node.right)) {
- unival = false;
- }
- if (!node.value.equals(node.right.value)) {
- unival = false;
- }
- }
- if (unival) {
- count++;
- }
- return unival;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement