📌  相关文章
📜  国际空间研究组织 | ISRO CS 2014 |问题 70(1)

📅  最后修改于: 2023-12-03 15:23:03.688000             🧑  作者: Mango

ISRO CS 2014 - Question 70

Introduction

The International Space Research Organization (ISRO) is India's national space agency, which is responsible for the nation's space program. In 2014, ISRO conducted a recruitment exam for the post of Computer Science (CS) Engineer. Question 70 of the exam was related to programming and algorithm design.

Problem Description

The problem statement is as follows:

You are given a binary tree consisting of 'n' nodes. Each node of the tree has a positive integer value. Your task is to count the number of unival subtrees in the given binary tree. An unival subtree is a subtree in which all nodes have the same value.

Approach

The problem can be solved by recursive traversal of the binary tree. We will start with the root of the binary tree and check if it is a unival subtree or not. If it is a unival subtree, we increment our count. We will then recursively check for its left and right child nodes.

To determine a unival subtree, we will compare the value of the current node with its left and right child nodes. If they all have the same value, the subtree is a unival subtree. We will return the value of the root node to the parent node and continue our traversal.

The code snippet to solve the problem is as follows:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def countUnivalSubtrees(self, root: TreeNode) -> int:
        self.count = 0
        
        def is_unival(node):
            if not node:
                return True
            
            left = is_unival(node.left)
            right = is_unival(node.right)
            
            if left and right:
                if node.left and node.val != node.left.val:
                    return False
                if node.right and node.val != node.right.val:
                    return False
                
                self.count += 1
                return True
            
            return False
        
        is_unival(root)
        return self.count
Conclusion

In this problem, we learned how to recursively traverse a binary tree and count the number of unival subtrees in it. The problem can be solved efficiently using a recursive approach.