Check Whether a Binary Tree Is a Fibonacci Tree in O(h) Time
Problem: Check Whether a Binary Tree Is a Fibonacci Tree (O(h))
Given the root root of a binary tree, define a Fibonacci Tree (Fib Tree) as follows:
- For every non-null node
node:- If
nodeis a leaf, it satisfies the property. - If
nodehas both a left childLand a right childR, then it must hold that:node.val = L.val + R.val- and both subtrees rooted at
LandRare Fibonacci Trees.
- If
- If a node has exactly one child, the tree is not a Fibonacci Tree.
Implement a function that determines whether the tree is a Fibonacci Tree, with the constraint:
- Required time complexity is O(h) where
his the height of the tree (not the number of nodes).
Note: The interview emphasized that
nrefers to the tree heighth, so you must avoid traversing the entire tree.
Input format (for testing here)
The tree is given as a level-order array, where null denotes a missing node.
Output format
Print true or false.
Constraints
0 <= number of nodes <= 2 * 10^5-10^9 <= node.val <= 10^9- Tree height
hcan be up to2 * 10^5
Examples
- Input:
[3,1,2] - Output:
true
- Input:
[3,1,null] - Output:
false
- Input:
[5,2,2,1,1,1,1] - Output:
true
- Input:
[4,1,2] - Output:
false
- Input:
[] - Output:
true
Example
Unlock to view complete problem details
and practice with sample input/output
Was this article helpful?
View Test Cases & Run Code requires membership
Standard Input
Execution Result:
