In a Red-Black Tree, the maximum height of a node is at most twice the minimum height (The four Red-Black tree properties make sure this is always followed). Given a Binary Search Tree, we need to check for following property.
For every node, length of the longest leaf to node path has not more than twice the nodes on shortest path from node to leaf.
12 40 \ / \ 14 10 100 \ / \ 16 60 150 Cannot be a Red-Black Tree It can be Red-Black Tree with any color assignment Max height of 12 is 1 Min height of 12 is 3 10 / \ 5 100 / \ 50 150 / 40 It can also be Red-Black Tree
Expected time complexity is O(n). The tree should be traversed at-most once in the solution.
We strongly recommend to minimize the browser and try this yourself first.
For every node, we need to get the maximum and minimum heights and compare them. The idea is to traverse the tree and for every node check if it’s balanced. We need to write a recursive function that returns three things, a boolean value to indicate the tree is balanced or not, minimum height and maximum height. To return multiple values, we can either use a structure or pass variables by reference. We have passed maxh and minh by reference so that the values can be used in parent calls.
Time Complexity: Time Complexity of above code is O(n) as the code does a simple tree traversal.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- How to determine if a binary tree is height-balanced?
- Practice questions on Height balanced/AVL Tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Height of binary tree considering even level leaves only
- Check if the given binary tree has a sub-tree with equal no of 1's and 0's | Set 2
- Height of a complete binary tree (or Heap) with N nodes
- Relationship between number of nodes and height of binary tree
- Iterative Method to find Height of Binary Tree
- Check if a binary tree is subtree of another binary tree | Set 2
- Check whether a binary tree is a full binary tree or not
- Check if a binary tree is subtree of another binary tree | Set 1
- Check whether a given binary tree is skewed binary tree or not?
- Find Height of Binary Tree represented by Parent array