230. Kth Smallest Element in a BST

该博客介绍了如何在二叉搜索树中找到第K小的元素。通过两种方法实现:一是使用中序遍历获取所有节点值并返回第K小的值;二是利用栈进行非递归的中序遍历,先将左子树压栈,然后弹出K-1个最小值,最后返回栈顶元素作为第K小的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

230. Kth Smallest Element in a BST

Description

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

Thoughts

We can simply use inorder traversal to find the kth elements.
We can also use stack to implement inorder traversal without using recursive coding.

Code

inorder traversal

'''
use in order traversal to get all the node.val in a list
the kth elements is the kth smallest
'''
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        value_list = self.inorder_traversal(root)
        return value_list[k - 1]
            
    def inorder_traversal(self, root):
        if not root:
            return []
        left = self.inorder_traversal(root.left)
        right = self.inorder_traversal(root.right)
        return left + [root.val] + right
	}

stack

    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
    '''
    initialize an empty stack
    '''
        stack = []
    '''
    put the root and all the left nodes to the stack
    now the stack has root in the bottom
    the smallest node (left most node) is on the top
    '''
        while root:
            stack.append(root)
            root = root.left
    '''
    we need to get the Kth smallest so we need to pop k-1 times
    pop the smallest node first
    '''
        for i in range(k-1):
        	node = stack.pop()
    '''
    if the node has right subtree: 
    	based on BST definition, all the nodes in the right 	
    	subtree are smaller than the parent node of the current 		
    	node.
    			8
    		  /
    		2
    	  /  \
    	1	  4
    		 / \
    		3	5
    	in stack: 1 -- 2 -- 8
    	pop 1 frist and then pop 2
    	3, 4, 5 in the right subtree are all smaller than 8
    	need to append them in the stack above 8
    	and they will be pop before 8
    '''      
            if node.right:
                node = node.right
    '''
    look at the right node, and put all the left nodes in stack
    3 -- 4 -- 8
    '''
                while node:
                    stack.append(node)
                    node = node.left
     '''
     pop 3, 4 and 4 has right node 5
     put 5 in : 5 -- 8
     '''
        return stack[-1].val
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值