劍指offer46 — 二叉搜索樹的第k個結點
題目
給定一棵二叉搜索樹,請找出其中的第k小的結點。例如, (5,3,7,2,4,6,8) 中,按結點數值大小順序第三小結點的值爲4。
分析
由於二叉搜索樹的特殊性,中序遍歷第k個結點即爲從小到大的第k個數據。即寫一箇中序遍歷的函數,調用並利用一個輔助數組進行遍歷結果存儲即可。
代碼
# -*- 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):
# write code here
retList = []
def preOrder(pRoot):
# 中序遍歷
if pRoot == None:
return None
preOrder(pRoot.left)
retList.append(pRoot)
preOrder(pRoot.right)
preOrder(pRoot)
if len(retList) < k or k < 1:
return None
return retList[k-1]