题目:给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
分析:二叉搜素树就是二叉树的中序遍历
import java.util.Stack;
public class KthNode2 {
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public static TreeNode KthNode(TreeNode pRoot, int k) {
if(pRoot==null||k==0){
return null;
}
int count =0;
Stack<TreeNode> stack=new Stack<TreeNode>();
while(pRoot!=null||!stack.isEmpty()){
while(pRoot!=null){
stack.push(pRoot);
pRoot=pRoot.left;
}
if(!stack.isEmpty()){
count++;
pRoot=stack.pop();
if(count==k){
return pRoot;
}
pRoot=pRoot.right;
}
}
return null;
}
public static void main(String[] args) {
TreeNode head=new TreeNode(5);
head.left=new TreeNode(3);
head.right=new TreeNode(7);
head.left.left=new TreeNode(2);
head.left.right=new TreeNode(4);
head.right.left=new TreeNode(6);
head.right.right=new TreeNode(8);
System.out.println(KthNode(head,8));
}
}
是递增的树。
本文介绍了一种在二叉搜索树中寻找第K小节点的算法,通过中序遍历的方式,利用栈数据结构实现了递增顺序访问树节点,最终找到目标节点。示例代码使用Java实现。
&spm=1001.2101.3001.5002&articleId=84991915&d=1&t=3&u=e4a1d80ba2ce4474ace6eb4ecbd27e16)
202

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



