leetcode -- 230. Kth Smallest Element in a BST 【遍历 + 计数】

题目

Given a binary search tree, write a function kthSmallest to find thekth 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?


题意

给定一个二叉搜索树,通过一个方法kthSmalllest 来知道第k 小的元素。(注意题目中的假设)


分析及代码

方法1(全局计数器):

  • 二叉搜索树的定义及特点
    二叉排序树或者是一棵空树,或者是具有下列性质的 二叉树
    (1)若左子树不空,则左子树上所有结点的值均小于或等于它的 根结点的值;
    (2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;
    (3)左、右子树也分别为二叉排序树;
  • 特点的运用】从小到大排列  ---> 中序遍历 ;从大到小排列 -->  中序遍历 + 栈(或者以右子树开始,进行中序遍历)
  • 参数分析】观察可知,方法的参数有两个,其中一个用来表示TreeNode(提供遍历的必要),k 用来说明限制,也告诉了我们的目标
  • 返回值】最终的结果。我们需要在遍历达到目标的时候,不断从调用层次深处到顶层传递。(可能在调用底层某个点就已经达到目标了,返回时需保持)
  • 全局计数器】计数,&& count 与 k构成限制条件。

public class KthSmallest {
	int count = 0;
	
	public int kthSmallest(TreeNode root, int k) {
		TreeNode tgt = findTreeNode(root, k);
		return tgt.val;
	}

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

反例:

下面程序也正确,只不过有大量重复操作。(体现在countNodes处)(原程序地址

public int kthSmallest(TreeNode root, int k) {
        int count = countNodes(root.left);
        if (k <= count) {
            return kthSmallest(root.left, k);
        } else if (k > count + 1) {
            return kthSmallest(root.right, k-1-count); // 1 is counted as current node
        }
        
        return root.val;
    }
    
    public int countNodes(TreeNode n) {
        if (n == null) return 0;
        
        return 1 + countNodes(n.left) + countNodes(n.right);
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值