Kth Smallest Element in a BST

原创 2015年07月15日 15:39:04

在BST中找到第k小的数。
递归

class Solution:
    # @param {TreeNode} root
    # @param {integer} k
    # @return {integer}
    def kthSmallest(self, root, k):
        num_left_nodes=self.num_nodes(root.left)
        print num_left_nodes
        if num_left_nodes+1>k:
            return self.kthSmallest(root.left,k)
        elif num_left_nodes+1==k:
            return root.val
        else:
            return self.kthSmallest(root.right,k-num_left_nodes-1)
    def num_nodes(self,root):
        if root is None:
            return 0
        else:
            return self.num_nodes(root.left)+self.num_nodes(root.right)+1
版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

#leetcode#Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. N...

230. Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. ...

精选:深入理解 Docker 内部原理及网络配置

网络绝对是任何系统的核心,对于容器而言也是如此。Docker 作为目前最火的轻量级容器技术,有很多令人称道的功能,如 Docker 的镜像管理。然而,Docker的网络一直以来都比较薄弱,所以我们有必要深入了解Docker的网络知识,以满足更高的网络需求。

230. Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Not...

230. Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.Note...

Kth Smallest Element in a BST

230. Kth Smallest Element in a BSTProblem Given a binary search tree, write a function kthSmallest...

[leetcode] Kth Smallest Element in a BST

题目链接在此 Given a binary search tree, write a function kthSmallest to find the kth smallest elemen...

leetcode--Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.Note...

230. Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. ...

Kth Smallest Element in a BST

题目Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.No...

【leetcode】230. Kth Smallest Element in a BST

一、题目描述 Given a binary search tree, write a function kthSmallest to find the kth smallest elem...
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)