Extract Kth Character From The Rope Tree — LeetCode 2689 Python Solution

EasyLeetCode PremiumTreeDepth-First SearchBinary Tree
Problem
#2689
Reading time
3 min

The problem

You are given the root of a binary tree and an integer k. Besides the left and right children, every node of this tree has two other properties, a string node.val containing only lowercase English letters (possibly empty) and a non-negative integer node.len.

Example

Input
root = [10,4,"abcpoe","g","rta"], k = 6
Output
"b"
Explanation
In the picture below, we put an integer on internal nodes that represents node.len, and a string on leaf nodes that represents node.val.

Python solution

Python
# Definition for a rope tree node.
# class RopeTreeNode(object):
#     def __init__(self, len=0, val="", left=None, right=None):
#         self.len = len
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def getKthCharacter(self, root: Optional[object], k: int) -> str:
        def dfs(root):
            if root is None:
                return ""
            if root.len == 0:
                return root.val
            return dfs(root.left) + dfs(root.right)

        return dfs(root)[k - 1]

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2689. Extract Kth Character From The Rope 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 2689. Extract Kth Character From The Rope Tree?
LeetCode 2689. Extract Kth Character From The Rope Tree is rated Easy on LeetCode.
What is the time complexity of LeetCode 2689. Extract Kth Character From The Rope Tree?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 2689. Extract Kth Character From The Rope Tree?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 2689. Extract Kth Character From The Rope Tree cover?
LeetCode 2689. Extract Kth Character From The Rope Tree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.
Is LeetCode 2689. Extract Kth Character From The Rope Tree a premium problem?
Yes. LeetCode 2689. Extract Kth Character From The Rope 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