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

    二叉搜索树的第k个结点

    题目描述

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

    使用栈遍历树, 当遍历到右子树时, 已经是从最小的开始了

    class Solution {
    public:
        TreeNode* KthNode(TreeNode* pRoot, int k)
        {
            if(pRoot==nullptr||k==0)
                return nullptr;
            stack<TreeNode*> stack;
            int count = 0;
            TreeNode* node = pRoot;
            do{
                if(node!=nullptr){
                    stack.push(node);
                    node = node->left;
                }else{
                    node = stack.top();
                    stack.pop();
                    count++;
                    if(count==k)
                        return node;
                    node = node->right;
                }
            }while(node!=nullptr||!stack.empty());
            return nullptr;
        }
    };
    

    中序遍历, 比较简陋

    class Solution {
    public:
        vector<TreeNode *> vt;
        
        void  inOrder(TreeNode *pRoot) {
            if (nullptr == pRoot)
                return;
            inOrder(pRoot->left);
            vt.push_back(pRoot);
            inOrder(pRoot->right);
        }
        
        TreeNode* KthNode(TreeNode* pRoot, int k)
        {
            if ((nullptr == pRoot) || (k < 1))
                return nullptr;
            inOrder(pRoot);
            if (k > vt.size())
                return nullptr;
            
            TreeNode * ret = nullptr;
            
            for (int i = 0; i < k; i++) {
                ret = vt[i];
            }
            
            return ret;
        }
    };
    
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };
    
  • 相关阅读:
    vue的选项
    css(3)基础知识查漏补缺
    总结获取网页相关的一些宽高
    vue的全局api(二)
    vue的全局api
    vue的内部指令
    Java File
    Java File IO学习笔记
    systemctl介绍
    java学习笔记一(20180319)
  • 原文地址:https://www.cnblogs.com/hesper/p/10562136.html
Copyright © 2011-2022 走看看