题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如,(5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
何为二叉搜索树?树中每一个结点的值都大于左子结点且小于右子结点。所以若中序遍历二叉搜索树,得到的结果就是由小到大排序的有序数列。
解题思路—中序遍历-递归版:通过递归进行中序遍历,当遍历到第k个数值的时候,输出结果。
✨解题思路—中序遍历-递归简化版:这段代码特别简洁,对上面的代码做了简化,但是却不太易懂,特别是if(node != null) return node;
这段代码,它的主要目的就是在找到k结点后能够沿着递归层返回主函数。使用debug能帮助解读代码!
解题思路—中序遍历-非递归堆栈:使用堆栈进行深度遍历,当弹出第k个结点时则输出。
Java解题—中序遍历-递归版
public class Solution {
public int ind = 0;
public TreeNode node = null;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot==null || k==0)
return null;
ind = k;
preOrder(pRoot);
return node;
}
public void preOrder(TreeNode root){
if(root!=null && node==null){
preOrder(root.left);
ind--;
if(ind==0){
node = root;
return;
}
preOrder(root.right);
}
}
}
Java解题—中序遍历-递归简化版
public class Solution {
public int ind = 0;
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot != null){
TreeNode node = KthNode(pRoot.left, k);
if(node != null) // 找到k结点后能够沿着递归层返回主函数
return node;
ind++;
if(ind == k)
return pRoot;
node = KthNode(pRoot.right, k);
if(node != null) // 找到k结点后能够沿着递归层返回主函数
return node;
}
return null;
}
}
Java解题—中序遍历-非递归堆栈
import java.util.Stack;
public class Solution {
TreeNode KthNode(TreeNode pRoot, int k)
{
if(pRoot==null || k==0)
return null;
Stack<TreeNode> stack = new Stack<>();
int count = 0;
TreeNode node = pRoot;
while(node!=null || !stack.isEmpty()){
while(node!=null){
stack.push(node);
node = node.left;
}
node = stack.pop();
count++;
if(count==k)
return node;
node = node.right;
}
return null;
}
}