Height of Special Binary Tree — LeetCode 2773 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchBreadth-First SearchBinary Tree
Problem
#2773
Reading time
4 min

The problem

You are given a root, which is the root of a special binary tree with n nodes. The nodes of the special binary tree are numbered from 1 to n.

Example

Input
root = [1,2,3,null,null,4,5]
Output
2
Explanation
The given tree is shown in the following picture. Each leaf's left child is the leaf to its left (shown with the blue edges). Each leaf's right child is the leaf to its right (shown with the red edges). We can see that the graph has a height of 2.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def heightOfTree(self, root: Optional[TreeNode]) -> int:
        def dfs(root: Optional[TreeNode], d: int):
            nonlocal ans
            ans = max(ans, d)
            if root.left and root.left.right != root:
                dfs(root.left, d + 1)
            if root.right and root.right.left != root:
                dfs(root.right, d + 1)

        ans = 0
        dfs(root, 0)
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2773. Height of Special Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2773. Height of Special Binary Tree?
LeetCode 2773. Height of Special Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 2773. Height of Special Binary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2773. Height of Special Binary Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2773. Height of Special Binary Tree cover?
LeetCode 2773. Height of Special Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.
Is LeetCode 2773. Height of Special Binary Tree a premium problem?
Yes. LeetCode 2773. Height of Special Binary Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview