LeetCode - Kth Smallest Element in a BST
Posted IncredibleThings
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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: You may assume k is always valid, 1 ≤ k ≤ BST‘s total elements. Example 1: Input: root = [3,1,4,null,2], k = 1 Output: 1 Example 2: Input: root = [5,3,6,2,4,null,null,1], k = 3 Output: 3 Follow up: What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?
那么这道题给的提示是让我们用BST的性质来解题,最重要的性质是就是左<根<右,那么如果用中序遍历所有的节点就会得到一个有序数组。所以解题的关键还是中序遍历啊。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { //inorder traversal public int kthSmallest(TreeNode root, int k) { Stack<TreeNode> stack = new Stack<>(); TreeNode p = root; int result = 0; while(!stack.isEmpty() || p != null){ if(p != null){ stack.push(p); p = p.left; } else{ TreeNode t = stack.pop(); k--; if(k == 0){ result = t.val; } p = t.right; } } return result; } }
以上是关于LeetCode - Kth Smallest Element in a BST的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 378. Kth Smallest Element in a Sorted Matrix
LeetCode-230. Kth Smallest Element in a BST
Leetcode 230. Kth Smallest Element in a BST
LeetCode - Kth Smallest Element in a BST
Leetcode 230: Kth Smallest Element in a BST
java Kth Smallest in 2 Sorted Array #TwoSum #LeetCode #PriorityQueue