给定一棵二叉搜索树,请找出其中第k大的节点。
解法一:使用递归和中序遍历
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
if not root or k==0:
return None
target = []
def kth(node): # 中序遍历得到排序的数组
if node.right:
kth(node.right)
target.append(node.val)
if node.left:
kth(node.left)
kth(root)
print(target)
return target[k-1]
解法二:使用循环
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
if not root or k==0:
return None
lists = []
while k!=0: # 当k==0时,直接返回节点对应的值
if root: # 如果当前节点不为空,遍历其右节点
lists.append(root)
root = root.right
else: # 如果当前节点为空,返回队列中的最后一个节点值
root = lists.pop()
if k==1:
return root.val
else:
k-=1
root = root.left # 对当前节点的左子树进行循环