Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. The length of path between two nodes is represented by the number of edges between them.
Input : 2 / \ 7 2 / \ \ 1 1 2 Output : 2 Input : 4 / \ 4 4 / \ \ 4 9 5 Output : 3
The idea is to recursively traverse given binary tree. We can think of any path (of nodes with the same values) in up to two directions(left and right) from it’s root. Then, for each node, we want to know what is the longest possible length extending in the left and the longest possible length extending in the right directions. The longest length that extends from the node will be 1 + length(node->left) if node->left exists, and has the same value as node. Similarly for the node->right case.
While we are computing lengths, each candidate answer will be the sum of the lengths in both directions from that node. We keep updating these answers and return the maximum one.
- Time complexity : O(n), where n is the number of nodes in tree as every node is processed once.
- Auxiliary Space : O(h), where h is the height of tree as recursion can go upto depth h.
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.
- Print the longest leaf to leaf path in a Binary tree
- Print the longest path from root to leaf in a Binary tree
- Length of longest straight path from a given Binary Tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Check if two nodes are on same path in a tree | Set 2
- Longest path in an undirected tree
- Maximum sub-tree sum in a Binary Tree such that the sub-tree is also a BST
- Check if a binary tree is subtree of another binary tree | Set 1
- Binary Tree to Binary Search Tree Conversion
- Check if a binary tree is subtree of another binary tree | Set 2
- Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
- Check whether a binary tree is a full binary tree or not
- Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
- Minimum swap required to convert binary tree to binary search tree
- Binary Tree | Set 3 (Types of Binary Tree)
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Binary Tree to Binary Search Tree Conversion using STL set
- Check whether a given binary tree is skewed binary tree or not?
- Difference between Binary Tree and Binary Search Tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative