題目描述:
給定一棵二叉搜索樹,請找出其中的第k小的結點。例如, (5,3,7,2,4,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 __init__(self):
self.list = []
def KthNode(self, pRoot, k):
# write code here
if pRoot == None or k == 0:
return None
self.mid(pRoot)
if k > len(self.list):
return None
return self.list[k-1]
def mid(self, pRoot):
if pRoot:
self.mid(pRoot.left)
self.list.append(pRoot)
self.mid(pRoot.right)