zoukankan      html  css  js  c++  java
  • 剑指offer 二叉搜索树的第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 public:
    13     int count = 0;
    14     TreeNode* KthNode(TreeNode* pRoot, int k) {
    15         if(pRoot != NULL) {
    16             TreeNode* temp = KthNode(pRoot->left,k);
    17             if(temp != NULL)
    18                 return temp;
    19             count ++;
    20             if(count == k)
    21                 return pRoot;
    22             temp = KthNode(pRoot->right,k);
    23             if(temp != NULL)
    24                 return temp;
    25         }
    26         return NULL;
    27     }
    28 };

    我的笔记:

      二叉搜索树按照中序遍历的顺序打印出来正好就是排序好的顺序。所以,按照中序遍历顺序找到第k个结点就是结果。

  • 相关阅读:
    git知识点总结
    自动化进阶
    unittest单元测试框架
    自动化测试模型
    webdriver
    python文件处理
    uva 11077 置换
    poj 1066 Treasure Hunt
    poj 2661 Factstone Benchmark
    hdu 4180
  • 原文地址:https://www.cnblogs.com/john1015/p/13132308.html
Copyright © 2011-2022 走看看