/**
* Definition for a rope tree node.
* type RopeTreeNode struct {
* len int
* val string
* left *RopeTreeNode
* right *RopeTreeNode
* }
*/
func getKthCharacter(root *RopeTreeNode, k int) byte {
if root.len == 0{
return root.val[k-1]
}
left := 0
if root.left != nil{
left = root.left.len
if left == 0{
left = len(root.left.val)
}
}
if left >= k{
return getKthCharacter(root.left, k)
}else{
return getKthCharacter(root.right, k-left)
}
}
# 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:
"""
:type root: Optional[RopeTreeNode]
"""
ans = None
def dfs(node, cnt):
if not node or cnt==k: return cnt
if node.len==0:
for c in node.val:
cnt += 1
if cnt==k:
nonlocal ans
ans = c
elif cnt+node.len<k:
cnt += node.len
else:
cnt = dfs(node.left, cnt)
cnt = dfs(node.right, cnt)
return cnt
cnt = dfs(root, 0)
return ans
# 递归
def getKthCharacter2(self, root: Optional[object], k: int) -> str:
if root.len==0:
return root.val[k-1]
if root.left:
if root.left.len==0:#字符串了
g=len(root.left.val)
return root.left.val[k-1] if g>=k else self.getKthCharacter2(root.right,k-g)
else:#不是字符串
if root.left.len>=k:
return self.getKthCharacter2(root.left,k)
else:
return self.getKthCharacter2(root.right,k-root.left.len)
return self.getKthCharacter2(root.right,k)