【题目描述】
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
【解题思路】
二叉搜索树的定义就是:若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉搜索树。
此题有两种解法,法一就是使用递归的方法中序遍历二叉树,将结果都存在一个数组中,递归遍历完成后,输出索引为k-1的结点,用Python实现的代码如下:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回对应节点TreeNode
def MidTravel(self, pRoot):
if pRoot == None:
return
self.MidTravel(pRoot.left)
res.append(pRoot)
self.MidTravel(pRoot.right)
def KthNode(self, pRoot, k):
# write code here
global res
res = []
self.MidTravel(pRoot)
if pRoot == None or k<=0 or k>len(res): return None
return res[k-1]
此题的第二种解法是用栈来模拟递归操作,这样可以不用遍历整个二叉树就找到第k小的结点,节省了时间和空间。因为在计算机底层结构中,递归操作就是用栈这种数据结构来实现的,即:进入新递归的时候压栈、当前递归返回值的时候出栈。在这道题中,重复以下步骤:
- 将左子树一直压栈,直到左子树为空
- 弹出栈顶元素并判断是不是第k小的元素,如果是,则直接返回,程序结束
- 将栈顶元素的右子树压栈
用Python实现的代码如下:
# -*- 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
if pRoot == None or k<=0: return None
res = []
count = 0
while res or pRoot:
while pRoot:
res.append(pRoot)
pRoot = pRoot.left
pRoot = res.pop()
count += 1
if count == k:
return pRoot
pRoot = pRoot.right
return None