跳至主要內容

230. 二叉搜索树中第K小的元素

T4mako算法数组前缀和小于 1 分钟

230. 二叉搜索树中第K小的元素

中等

题目描述open in new window

解法:中序遍历

class Solution {
    int num = 0;
	int res;
	public int kthSmallest(TreeNode root, int k) {
		if(root.left != null) {
			kthSmallest(root.left, k);
		}
		num++;
		if(num == k) res = root.val;
		if(root.right != null) {
			kthSmallest(root.right, k);
		}
		return res;
    }
}
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.5