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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- How to determine if a binary tree is height-balanced?
- Count Balanced Binary Trees of Height h
- Practice questions on Height balanced/AVL Tree
- Check if the Binary Tree contains a balanced BST of size K
- Shortest path between two nodes in array like representation of binary tree
- Sum of specially balanced nodes from a given Binary Tree
- Maximum height of the binary search tree created from the given array
- Count balanced nodes present in a binary tree
- Create Balanced Binary Tree using its Leaf Nodes without using extra space
- Check whether a given binary tree is skewed binary tree or not?
- Iterative Method to find Height of Binary Tree
- Find Height of Binary Tree represented by Parent array
- Relationship between number of nodes and height of binary tree
- Height of a complete binary tree (or Heap) with N nodes
- Calculate height of Binary Tree using Inorder and Level Order Traversal
- Find height of a special binary tree whose leaf nodes are connected
- Height of binary tree considering even level leaves only
- Print middle level of perfect binary tree without finding height
- Print the nodes of the Binary Tree whose height is a Prime number
- Height of n-ary tree if parent array is given