网站建设费记什么科目,网站建设 图书管理网站,网络营销策划方案设计,安卓app软件制作工具一、题目 给定一颗二叉搜索树#xff0c;请找出其中的第k大的结点。例如#xff0c; 5 / \ 3 7 /\ /\ 2 4 6 8 中#xff0c;按结点数值大小顺序第三个结点的值为4。 二、解法 1 package algorithm7;2 3 public class KthNode62 {4 public static void main(String[] ar…一、题目 给定一颗二叉搜索树请找出其中的第k大的结点。例如 5 / \ 3 7 /\ /\ 2 4 6 8 中按结点数值大小顺序第三个结点的值为4。 二、解法 1 package algorithm7;2 3 public class KthNode62 {4 public static void main(String[] args) {5 KthNode62 kth new KthNode62();6 TreeNode t1 new TreeNode(5);7 TreeNode t2 new TreeNode(3);8 TreeNode t3 new TreeNode(7);9 TreeNode t4 new TreeNode(2);
10 TreeNode t5 new TreeNode(4);
11 TreeNode t6 new TreeNode(6);
12 TreeNode t7 new TreeNode(8);
13 t1.left t2;
14 t1.right t3;
15 t2.left t4;
16 t2.right t5;
17 t3.left t6;
18 t3.right t7;
19 TreeNode t kth.KthNode(t1,8);
20 System.out.println(t.val);
21 }
22 int index 0;//计数器
23 //用中序遍历左 根 右
24 public TreeNode KthNode(TreeNode pRoot, int k)
25 {
26 if(pRoot ! null){
27 TreeNode node KthNode(pRoot.left,k);//左
28 if(node ! null)//表示找到了结点
29 return node;
30
31 index;//根
32 if(index k)
33 return pRoot;//找到了
34
35 node KthNode(pRoot.right,k);//右
36 if(node ! null)//表示找到了结点
37 return node;
38 }
39 return null;//遍历完了 返回空 或者该结点为空
40 }
41 } 转载于:https://www.cnblogs.com/fankongkong/p/7462149.html