结论:二叉搜索树的中序遍历是有序的
如力扣230题
题目描述:
给定一个二叉搜索树的根节点 root
,和一个整数 k
,请你设计一个算法查找其中第 k
个最小元素(从 1 开始计数)。
例:
输入:root = [3,1,4,null,2], k = 1 输出:1
我们可以利用这一结论,将输入的二叉搜索树,进行中序遍历,很快能够处理出结果。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
//全局变量
private int k;
private int res;
public int kthSmallest(TreeNode root, int k) {
this.k=k;
dfs(root);
return res;
}
//中序遍历
private void dfs(TreeNode root){
if(root==null){
return;
}
dfs(root.left);
k--;
if(k==0){
res = root.val;
return;
}
dfs(root.right);
}
}