But it doesn't have to end here! Sign up for the 7-day coding interview crash course and you'll get a free Interview Cake problem every week.
You're in!
Write a function to see if a binary tree is "superbalanced" (a new tree property we just made up).
A tree is "superbalanced" if the difference between the depths of any two leaf nodes is no greater than one.
Here's a sample binary tree node class:
@interface ICKBinaryTreeNode : NSObject
@property (nonatomic) NSInteger value;
@property (nonatomic) ICKBinaryTreeNode *left;
@property (nonatomic) ICKBinaryTreeNode *right;
- (instancetype)initWithValue:(NSInteger)value;
- (ICKBinaryTreeNode*)insertLeft:(NSInteger)leftValue;
- (ICKBinaryTreeNode*)insertRight:(NSInteger)rightValue;
@end
@implementation ICKBinaryTreeNode
- (instancetype)initWithValue:(NSInteger)value {
if (self = [super init]) {
self.value = value;
}
return self;
}
- (ICKBinaryTreeNode*)insertLeft:(NSInteger)leftValue {
self.left = [[ICKBinaryTreeNode alloc] initWithValue:leftValue];
return self.left;
}
- (ICKBinaryTreeNode*)insertRight:(NSInteger)rightValue {
self.right = [[ICKBinaryTreeNode alloc] initWithValue:rightValue];
return self.right;
}
@end
Log in or sign up with one click to get immediate access to 3 free mock interview questions
We'll never post on your wall or message your friends.
Actually, we don't support password-based login. Never have. Just the OAuth methods above. Why?
time and space.
For time, the worst case is the tree is balanced and we have to iterate over all nodes to make sure.
For the space cost, we have two data structures to watch: depths and nodes.
depths will never hold more than three elements, so we can write that off as .
Because we’re doing a depth first search, nodes will hold at most nodes where is the depth of the tree (the number of levels in the tree from the root node down to the lowest node). So we could say our space cost is .
But we can also relate to . In a balanced tree, is . And the more unbalanced the tree gets, the closer gets to .
In the worst case, the tree is a straight line of right children from the root where every node in that line also has a left child. The traversal will walk down the line of right children, adding a new left child to nodes at each step. When the traversal hits the rightmost node, nodes will hold half of the total nodes in the tree. Half is , so our worst case space cost is .
Log in or sign up with one click to get immediate access to 3 free mock interview questions
We'll never post on your wall or message your friends.
Actually, we don't support password-based login. Never have. Just the OAuth methods above. Why?
Reset editor
Powered by qualified.io