剑指Offer 62. 二叉搜索树的第k个结点 (二叉搜索树)

Posted on 2018-10-18 11:01  _hqc  阅读(171)  评论(0编辑  收藏  举报

题目描述

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4。

例如,

5

/ \

3 7

/ \ / \

2 4 6 8

中,按结点数值大小顺序第三个结点的值为4。

题目地址

https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13&tqId=11215&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路

这棵树是二叉搜索树,首先想到的是二叉搜索树的一个特点:左子结点的值 < 根结点的值 < 右子结点的值。

遇到bst(二叉搜索树)想到中序遍历,先中序遍历,然后找出第k个结点。

Python

class TreeNode:
    def __init__(self,x):
        self.val = x
        self.left = None
        self.right = None
node1 = TreeNode(5)
node2 = TreeNode(3)
node3 = TreeNode(7)
node4 = TreeNode(2)
node5 = TreeNode(4)
node6 = TreeNode(6)
node7 = TreeNode(8)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node3.right = node7
class Solution:
    # 返回对应节点TreeNode
    def KthNode(self, pRoot, k):
        # write code here
    # 思路1
    #     if not pRoot or k <=0:
    #         return None
    #     res = []
    #     self.inOrder(pRoot,res)
    #     if len(res) < k:
    #         return None
    #     return res[k-1]
    # def inOrder(self, pRoot,res):
    #     if not pRoot:
    #         return None
    #     if pRoot.left:
    #         self.inOrder(pRoot.left,res)
    #     res.append(pRoot)
    #     if pRoot.right:
    #         self.inOrder(pRoot.right,res)
    # 思路2
        if not pRoot or k <= 0:
            return None
        treeStack,treeNode = [], []
        pNode = pRoot
        while pNode or len(treeStack):
            while pNode:
                treeStack.append(pNode)
                pNode = pNode.left
            if len(treeStack):
                pNode = treeStack.pop()
                treeNode.append(pNode)
                pNode = pNode.right
        if len(treeNode) < k:
            return None
        return treeNode[k-1]
if __name__ == '__main__':
    result = Solution().KthNode(node1,3)
    print(result.val)