标签:中序 return ret out 递归 时间 ati null kth
二叉搜索树中第K小的元素。题目即是题意。例子,
Example 1:
Input: root = [3,1,4,null,2], k = 1 3 / 1 4 2 Output: 1Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3 5 / 3 6 / 2 4 / 1 Output: 3
因为是BST所以大概率会碰到中序遍历inorder traversal,这一题也不例外。思路就是按照中序遍历的方法去遍历BST的节点,用count记录是否到K,输出第K个节点即可。我这里给的是递归的解法,比较方便。影子题671。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 private static int count; 3 private static int res; 4 5 public int kthSmallest(TreeNode root, int k) { 6 count = k; 7 helper(root); 8 return res; 9 } 10 11 public void helper(TreeNode root) { 12 if (root == null) { 13 return; 14 } 15 helper(root.left); 16 count--; 17 if (count == 0) { 18 res = root.val; 19 } 20 helper(root.right); 21 } 22 }
JavaScript实现
1 /** 2 * @param {TreeNode} root 3 * @param {number} k 4 * @return {number} 5 */ 6 var kthSmallest = function (root, k) { 7 let count = k; 8 let res = 0; 9 10 let helper = function (root) { 11 if (root == null) { 12 return; 13 } 14 helper(root.left); 15 count--; 16 if (count == 0) { 17 res = root.val; 18 } 19 helper(root.right); 20 } 21 helper(root); 22 return res; 23 };
[LeetCode] 230. Kth Smallest Element in a BST
标签:中序 return ret out 递归 时间 ati null kth
原文地址:https://www.cnblogs.com/aaronliu1991/p/12529119.html