230. Kth Smallest Element in a BST

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
    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值