题目描述
给定一颗二叉搜索树,请找出其中的第k小的结点。
思路
中序遍历
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
private int count = 0;
TreeNode KthNode(TreeNode pRoot, int k) {
TreeNode tmp = null;
if (pRoot != null) {
tmp = KthNode(pRoot.left, k);
if (tmp != null) {
return tmp;
}
count++;
if (count == k) return pRoot;
tmp = KthNode(pRoot.right, k);
if (tmp != null) {
return tmp;
}
}
return null;
}
}

本文介绍了一种通过中序遍历找到二叉搜索树中第K小结点的方法。具体实现中,使用递归的方式进行左子树、根节点、右子树的遍历,并记录已访问的节点数,当达到K时返回当前节点。
279

被折叠的 条评论
为什么被折叠?



