【Leetcode】Kth Smallest Element in a BST

题目链接: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:

  1. Try to utilize the property of a BST.
  2. What if you could modify the BST node's structure?
  3. The optimal runtime complexity is O(height of BST).
思路:
1、BST中序遍历的结果是对所有结点值逐渐增大的一个排列。用List保存遍历结果,返回List的第k个元素就行了。时间复杂度是O(n),空间复杂度是O(n)。
2、中序遍历,用计数器记录当前遍历的结点个数,当遍历到k个元素的时候返回该结点的val,无需保存遍历的结点,时间复杂度O(n),空间复杂度O(1)。
3、修改结点数据结构,在TreeNode结点加入leftCount,表示左孩子数目,根据结点的leftCount调整递归分支,它不会遍历所有结点,而是自上而下的路径,所以时间复杂度是O(height of BST)。
算法1:
	public int kthSmallest(TreeNode root, int k) {
		List<Integer> list = new ArrayList<Integer>();
		list = inOrder(root, list);
		return list.get(k - 1);
	}

	public List<Integer> inOrder(TreeNode p, List<Integer> order) {
		if (p != null) {
			order = inOrder(p.left, order);
			order.add(p.val);
			order = inOrder(p.right, order);
		}
		return order;
	}


算法2:
	int count = 0, result;

	public int kthSmallest(TreeNode root, int k) {
		if (root != null) {
			kthSmallest(root.left, k);
			count++;
			if (count == k) {
				result = root.val;
			}
			kthSmallest(root.right, k);
		}
		return result;
	}


算法3:
class newTreeNode { // BST
	newTreeNode left, right;
	int val, leftCount;// 记录左孩子个数

	newTreeNode(int val) {
		this.val = val;
	}
}
	int result;

	public int kthSmallest(newTreeNode root, int k) {
		if (root != null) {
			if (root.leftCount + 1 == k) {
				result = root.val;
			} else if (root.leftCount + 1 < k) {
				kthSmallest(root.right, k - (root.leftCount + 1));
			} else {
				kthSmallest(root.left, k);
			}
		}
		return result;
	}



阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yeqiuzs/article/details/49963013
个人分类: leetcode
所属专栏: Leetcode题解java版
上一篇【Leetcode】Convert Sorted Array to Binary Search Tree
下一篇【Leetcode】Balanced Binary Tree
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭