• 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 };
  • 相关阅读:
    「golang」go-micro指定consul地址
    「postgres」无数据则插入,有数据不做插入
    「postgres」导出数据以及分割数据
    「postgre」调整表结构
    「postgre」查看DB的物理占用空间
    「postgre」INT最大值
    「postgre」服务重启
    「golang」关于TIME_WAIT优化
    深入理解Spring Boot属性配置文件
    springboot 中的commandLineRunners接口
  • 原文地址:https://www.cnblogs.com/zle1992/p/8295838.html
Copyright © 2020-2023  润新知