【LeetCode】230. 二叉搜索树中第K小的元素(Java)

1、题目描述:

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 个最小的元素。

Note:
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。

示例 1:

输入: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
输出: 1

示例 2:

输入: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
输出: 3

2、思路:

      已经构建相关的二叉树,并给出二叉树根结点root,利用中序遍历对二叉树进行检索得出第K小的结点数值。

3、相关代码:

public class LeetSolution {
    public class TreeNode{
	    int val;
	    TreeNode left;
	    TreeNode right;
	    TreeNode(int x){
		    val = x;
	    }
    }
    private int index;    //确定当前结点数值是否为第K小
    public int kthSmallest(TreeNode root,int k) {
	if(root ==null)
		return 0;
                            //中序遍历
	int leftval = kthSmallest(root.left , k);
	if(k == index)
		return leftval;
	if(k == ++index)
		return root.val;
	return kthSmallest(root.right,k);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40849588/article/details/87126002