Leetcode---二叉搜索树中第K小的元素--递归

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

题目链接:二叉搜索树中第K小的元素

思路:
  • 中序遍历一个二叉搜索树,得到的是一个有序序列
  • 根据这个原理,我们使用递归遍历,仅需要找到第K次弹栈的元素即可
代码:
	int count = 0;
	int val = 0;
	public int kthSmallest(TreeNode root, int k) {
		kthSmallest1(root,k);
		return val;
    }
	public void kthSmallest1(TreeNode root, int k) {
		if(root!=null) {
        	kthSmallest1(root.left,k);
        	++count;
        	if(count==k) {
        		val = root.val;
        		return ;
        	}
        	kthSmallest1(root.right,k);
        }
	}

猜你喜欢

转载自blog.csdn.net/tiaochewang219/article/details/84654869
今日推荐