Similar Problems

Similar Problems not available

Root Equals Sum Of Children - Leetcode Solution

Companies:

LeetCode:  Root Equals Sum Of Children Leetcode Solution

Difficulty: Easy

Topics: tree binary-tree  

Problem statement:

Given a binary tree, you need to compute 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.

Example:

Input:

          5
         / \
        4   5
       / \   \
      1   1   5

Output: 2

Solution:

We can solve this problem by using recursion. We define a recursive function maxDepth(node) that returns the maximum length of the path with same value starting from the given node. If the left and right children of a node have the same value as the node, then we add their lengths to the maximum length. We also update the maximum value of the result as we traverse the tree.

The code for this approach will look something like this:

class Solution(object): def longestUnivaluePath(self, root): """ :type root: TreeNode :rtype: int """ self.ans = 0

    def maxDepth(node):
        if not node:
            return 0
        left = maxDepth(node.left)
        right = maxDepth(node.right)
        left = left + 1 if node.left and node.left.val == node.val else 0
        right = right + 1 if node.right and node.right.val == node.val else 0
        self.ans = max(self.ans, left + right)
        return max(left, right)
    
    maxDepth(root)
    return self.ans

Time Complexity:

The time complexity of this solution is O(n) since we need to traverse the entire tree only once.

Space Complexity:

The space complexity of this solution is O(h) where h is the height of the tree since we are using recursion and the maximum depth of the recursion stack is the height of the tree.

Root Equals Sum Of Children Solution Code

1