• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
kulukulu
博客园    首页    新随笔    联系   管理    订阅  订阅
leetcode 230 二叉搜索树中第K小的元素

方法1:统计每个节点的子节点数目,当k>左子树节点数目时向左子树搜索,k=左子树节点数目时返回根节点,否则向右子树搜索。

方法2:递归中序遍历,这里开了O(n)空间的数组。

class Solution {
public:
   vector<int> result;//中序遍历序列
    void myInorderTraversal(TreeNode* root) {
        if (root == NULL) {
            return;
        }
        //先遍历左子树
        if (root->left != NULL) {
            myInorderTraversal(root->left);
        }
        //遍历当前根节点
        result.push_back(root->val);
        //再遍历右子树
        if (root->right != NULL) {
            myInorderTraversal(root->right);
        }
    }
    int kthSmallest(TreeNode* root, int k) {
        myInorderTraversal(root);//中序遍历二叉搜索树
        return result[k - 1];
    }
};

 

方法3:非递归中序遍历

class Solution {
public:
    int kthSmallest(TreeNode *root, int k)
    {
        stack<TreeNode *> s;
        while (1)
        {
            if (root)
            {
                s.push(root);
                root = root->left;
                continue;
            }
            if (k == 1)
                return s.top()->val;
            root = s.top()->right;
            s.pop();
            k--;
        }
    }
};

 

posted on 2019-03-23 16:56  kulukulu  阅读(133)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3