题目:给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
解题思路:二叉搜索树的中序遍历是递增的序列,所以只要得到树的中序遍历即可以完成.其实也可以从左子树最左边走K个值,也能得到最终的答案.
中序遍历代码
class Solution:
# 返回对应节点TreeNode
def MidTree(self, root,nList):
if root:
if root.left:
self.MidTree(root.left, nList)
nList.append(root)
if root.right:
self.MidTree(root.right, nList)
def KthNode(self, pRoot, k):
# write code here
if pRoot:
nList = []
self.MidTree(pRoot,nList)
if k>0 and k <= len(nList) :
return nList[k-1]
else:
return None
else:
return None