https://leetcode.com/problems/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.
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?
Hint:
- Try to utilize the property of a BST.
- What if you could modify the BST node's structure?
- The optimal runtime complexity is O(height of BST).
解题思路:
重点是,利用BST的中序遍历是一个有序序列,再从中寻找第K小的值。
注意的是,step什么时候+1?显然是在遍历到每个节点的时候。
那么在那么多递归中,实际上只有下面一段才是真正的执行,dfs left和right都不需要+1。
if (step[0] == k) {
return root;
}
step[0]++;
带返回值的递归
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int kthSmallest(TreeNode root, int k) { int [] step = new int[1]; step[0] = 1; TreeNode res = dfs(root, k, step); if(res == null) { return -1; } return res.val; } public TreeNode dfs(TreeNode root, int k, int[] step) { if(root == null) { return null; } TreeNode res1 = dfs(root.left, k, step); if(res1 != null) { return res1; } if(step[0] == k) { return root; } step[0]++; TreeNode res2 = dfs(root.right, k, step); return res2; } }
不带返回值的递归
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int kthSmallest(TreeNode root, int k) { int [] step = new int[1]; step[0] = 1; int [] res = new int[1]; dfs(root, k, step, res); return res[0]; } public void dfs(TreeNode root, int k, int[] step, int[] res) { if(root == null) { return; } dfs(root.left, k, step, res); if(step[0] == k) { res[0] = root.val; step[0]++; return; } step[0]++; dfs(root.right, k, step, res); } }
或者直接将step赋值为k也可以,省去一个参数
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int kthSmallest(TreeNode root, int k) { int [] step = new int[1]; step[0] = k; int [] res = new int[1]; dfs(root, step, res); return res[0]; } public void dfs(TreeNode root, int[] step, int[] res) { if(root == null) { return; } dfs(root.left, step, res); if(step[0] == 1) { res[0] = root.val; step[0]--; return; } step[0]--; dfs(root.right, step, res); } }
参数使用数组的原因是Java无法pass by reference,或者使用全局变量,也是可以的。

浙公网安备 33010602011771号