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:
解题思路:
带返回值的递归
/** * 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,或者使用全局变量,也是可以的。