zoukankan      html  css  js  c++  java
  • 面试题63 二叉搜索树的第k个结点

    题目描述

    给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / 3 7 / / 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
     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     int count = 0;
    13 public:
    14     TreeNode* KthNode(TreeNode* pRoot, unsigned int k)
    15     {
    16         if(pRoot){ 
    17                 TreeNode *ret = KthNode(pRoot->left, k);
    18                 if(ret) return ret;
    19                 if(++count == k) return pRoot;
    20                 ret = KthNode(pRoot->right,k);
    21                 if(ret) return ret;
    22         }
    23         return nullptr;
    24     }
    25 };
  • 相关阅读:
    awk使用
    SQL VIEW(视图)
    crontab使用
    SecureCRT
    Python异常
    Python字符串
    Python字典,列表,元组
    Python路径
    vim插件
    Python类
  • 原文地址:https://www.cnblogs.com/wanderingzj/p/5375750.html
Copyright © 2011-2022 走看看