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

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

被折叠的 条评论
为什么被折叠?



