Box Interview Question

Implement a method to check if a tree is unival

Interview Answers

Anonymous

Dec 29, 2014

def unival(root): if not root: return True if root.left and root.val != root.left.val: return False if root.right and root.val != root.right.val: return False return unival(root.left) and unival(root.right)

1

Anonymous

Nov 6, 2014

Requires tree recursions with some changes

Anonymous

Sep 8, 2015

/* * Unival Tree: A tree in which all the node values are same */ public class UnivalTree{ int count = 0; //to count the unival trees public boolean unival(TreeNode root){ if(root == null) return true; boolean left = unival(root.left); boolean right = unival(root.right); if(left && right && (root.left == null || root.left.val == root.val) && (root.right == null || root.right.val == root.val)){ count++; return true; } return false; } }