您的位置:首页 > 编程语言 > Python开发

python剑指offer系列二叉搜索树的第k个结点

2018-03-17 10:08 197 查看
题目:
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 24 6 8 中,按结点数值大小顺序第三个结点的值为4。

思路:

中序遍历的二叉搜索树就是排序的

代码:# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
self.arr = []
self.midTravel(pRoot)
return self.arr[k-1] if 0 < k <= len(self.arr) else None
def midTravel(self,pRoot):
if pRoot == None:
return
self.midTravel(pRoot.left)
self.arr.append(pRoot)
self.midTravel(pRoot.right)

# write code here
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: