zoukankan      html  css  js  c++  java
  • 60、二叉搜索树的第k个结点

    一、题目

    给定一颗二叉搜索树,请找出其中的第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 }
  • 相关阅读:
    如何用cmd命令加密文件夹
    C++异常处理
    STRTOK
    如何生成Detours.lib——Detours的使用准备
    学习C++心得与值得一看的书
    工作两年后的感悟
    MFC十八个简单问题转载
    程序员的五种非技术错误 转载
    用VC写DLL中"error LNK2005: _DllMain@12 already defined"的错误
    CxImage
  • 原文地址:https://www.cnblogs.com/fankongkong/p/7462149.html
Copyright © 2011-2022 走看看