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

    题目描述
    给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / 3 7 / / 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
     
    解题思路:使用中序遍历进行遍历,得到的就是按照顺序的,当遍历到第k个就输出即可。
     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 public:
    13     //实现中序遍历,对于二叉搜索树中序遍历是按节点从小到大排序
    14     TreeNode *KthNodeCore(TreeNode *root, int &k)//注意此处k为引用,因为在操作过程中k改变
    15     {
    16         TreeNode *target = NULL;
    17         if(root->left != NULL)
    18         {
    19             target = KthNodeCore(root->left,k);
    20         }
    21         if(target == NULL)//无左节点且还未找到,返回其叶子节点的父节点,k--
    22         {
    23             if(k == 1)
    24                 target = root;
    25             k--;
    26         }
    27         if(target == NULL && root->right != NULL)//找右结点
    28         {
    29             target = KthNodeCore(root->right,k);
    30         }
    31         return target;
    32     }
    33     TreeNode* KthNode(TreeNode* pRoot, int k)
    34     {
    35         if(pRoot == NULL || k == 0)
    36             return NULL;
    37         return KthNodeCore(pRoot,k);
    38     }
    39 };
  • 相关阅读:
    pytest+allure生成测试报告
    pytest之fixture使用详解
    pytest框架介绍
    使用records库操作SQL并且查询MySQL数据库
    python模块之codecs
    项目总结
    第二阶段团队绩效评分
    软件发布2.0
    “随手记”开发记录day20
    “随手记”开发记录day19
  • 原文地址:https://www.cnblogs.com/qqky/p/7123227.html
Copyright © 2011-2022 走看看