Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one. Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.
FristFirst off, did I understand the question correctly? In other words, we are looking for a subtree in a tree (or rotation of it) that looks like:
root
/ \
leaf_1 leaf_2
/
leaf1_1
root / \ leaf_1 leaf_2 / leaf1_1
My initial idea was to count the depth of the tree and check if maxDepth maxDepth
- minDepthminDepth
< 2 (which requires 2 traversal) . But I think I found a more efficient solution. The trade-off is that we should keep the ref to the root. I assume n-ary Treetree.
Is this correct?
Is this correct?