劍指offer全集詳解python版——二叉搜索樹的第k個結點

題目描述:
給定一棵二叉搜索樹,請找出其中的第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)            
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章