剑指offer--63.二叉搜索树的第k个结点
程序员文章站
2022-07-10 20:14:18
...
题目:给定一棵二叉搜索树,请找出其中的第k大结点(题意应该是数字索引的第k个)
分析:中序遍历,则数是从小到大排列,第k大结点,即中序结果的k-1索引值
import java.util.*;
public class wr63KthNode {
//遍历所有,输出第k-1个结点
static ArrayList<TreeNode> list=new ArrayList<>();
public static TreeNode KthNode(TreeNode pRoot, int k){
if(pRoot==null || k==0){
return null;
}
inOrder(pRoot);
if(k>list.size()){
return null;
}
return list.get(k-1);
}
public static void inOrder(TreeNode root){
if(root!=null){
inOrder(root.left);
list.add(root);
inOrder(root.right);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root=new TreeNode(5);
TreeNode node1=new TreeNode(3);
TreeNode node2=new TreeNode(7);
TreeNode node3=new TreeNode(2);
TreeNode node4=new TreeNode(4);
TreeNode node5=new TreeNode(6);
TreeNode node6=new TreeNode(8);
root.left=node1;
root.right=node2;
node1.left=node3;
node1.right=node4;
node2.left=node5;
node2.right=node6;
TreeNode k=KthNode(root,3);
System.out.print(k.val+" ");
}
}