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

    题目描述

    给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / 3 7 / / 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。

    思路
    二叉搜索树的中序遍历的输出结果是拍好序的,直接输出第K个即可

     1 public class Solution {
     2     int time = 0;
     3     TreeNode KthNode(TreeNode root, int k){
     4         if(root==null) return null;
     5         TreeNode node =  KthNode(root.left,k);
     6         if(node!=null) return node;
     7         time++;
     8         if(time==k)
     9             return root;
    10         node =  KthNode(root.right,k);
    11           return node;
    12         
    13     }
    14 
    15 }

     20180321

     1 public class Solution {
     2     int time = 0;
     3     TreeNode res ;
     4     TreeNode KthNode(TreeNode root, int k)
     5     { 
     6         help(root,k);
     7         return res;
     8     }
     9     private void help(TreeNode root,int k){           
    10         if(root==null)
    11             return ;
    12         help(root.left,k);
    13         time++;
    14         if(time ==k)
    15             res = root;        
    16         help(root.right,k);       
    17     }
    18 }

    c++:20180731

     1 /*
     2 struct TreeNode {
     3     int val;
     4     struct TreeNode *left;
     5     struct TreeNode *right;
     6     TreeNode(int x) :
     7             val(x), left(NULL), right(NULL) {
     8     }
     9 };
    10 */
    11 class Solution {
    12     
    13 public:
    14     TreeNode* KthNode(TreeNode* root, int k)
    15     {
    16         int cnt = 0;
    17         stack<TreeNode*> s ;
    18         while(root!=NULL ||!s.empty()){
    19             while(root!=NULL){
    20                 s.push(root);
    21                 root = root->left;    
    22             }
    23             if(!s.empty()){
    24                 root = s.top();
    25                 s.pop();
    26                 cnt++;
    27                 if(cnt==k) return root;
    28                 root = root->right;
    29             }
    30         }
    31           return NULL;      
    32     }
    33     
    34 };
  • 相关阅读:
    MySQL基础知识-安装MySQL
    java 安装环境 疑问(1)
    java 安装环境
    “64位调试操作花费的时间比预期要长",无法运行调试解决办法
    office完全卸载
    完全卸载oraclean安装
    不能安装64位office提示已安装32位的
    java 之 基础加强(一)
    java 之 dom4j解析xml
    java 之 schema解析
  • 原文地址:https://www.cnblogs.com/zle1992/p/8295838.html
Copyright © 2011-2022 走看看