• 剑指offer系列——62.二叉搜索树的第k个结点


    Q:给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
    T:
    中序遍历,递归:

        int count = 0;
    public:
        TreeNode* KthNode(TreeNode* pRoot, unsigned int k)
        {
            if(pRoot){ 
                    TreeNode *ret = KthNode(pRoot->left, k);
                    if(ret) return ret;//第k个出现在left里面
                    if(++count == k) return pRoot;
                    ret = KthNode(pRoot->right,k);
                    if(ret) return ret;
            }
            return nullptr;
        }
    

    非递归:

        TreeNode *KthNode(TreeNode *pRoot, int k) {
            if (pRoot == nullptr)
                return nullptr;
            stack<TreeNode *> s;
            s.push(pRoot);
            TreeNode *node = pRoot->left;
            while (node || !s.empty()) {
                if (node) {
                    s.push(node);
                    node = node->left;
                } else {
                    node = s.top();
                    s.pop();
                    k--;
                    if (k == 0) {
                        return node;
                    }
                    node = node->right;
                }
            }
            return nullptr;
        }
    
  • 相关阅读:
    xunjian.sh
    192.168.50.235配置
    自动备份并删除旧日志
    bg和fg命令
    linux之sed用法
    正则表示第二行,第二列
    linux下redis安装
    Hma梳理
    linux 系统监控、诊断工具之 lsof 用法简介
    java的基本数据类型有八种
  • 原文地址:https://www.cnblogs.com/xym4869/p/12374205.html
Copyright © 2020-2023  润新知