zoukankan      html  css  js  c++  java
  • Kth Smallest Element in a BST

    题目:

    Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

    Note: 
    You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

     

    cpp:

    方法一:递归

    class Solution {
    public:
        int kthSmallest(TreeNode* root,int k){
            int result;
            inOrder(root,k,result);
            return result;
        }
    
        int n =0;
        void inOrder(TreeNode* root,int kth,int& kthVal){
            if(!root ) return;
            inOrder(root->left,kth,kthVal);
            n = n + 1;
            if(n == kth) {
                kthVal = root->val;
                return;
            }
            inOrder(root->right,kth,kthVal);
        }
    
    };

    方法2:栈

    class Solution{
    public:
        int kthSmallest(TreeNode* root,int k){
            stack<TreeNode*> stack;
            int result;
            TreeNode *cur = root;
            while(!stack.empty() || cur){
                if(cur){
                    stack.push(cur);
                    cur = cur->left;
                }else{
                    TreeNode* temp = stack.top();
                    stack.pop();
                    k--;
                    if(k==0) {
                        result = temp->val;
                        return result;
                    }
                    cur = temp->right;
                }
            }
    
            return result;
        }
    
    
    };
  • 相关阅读:
    销售类
    语法
    编辑技巧 word
    assert
    游戏摘录
    游戏类链接 财富导图
    读书笔记之C# delegate
    c# socket传输struct类型
    关于wcf中一些重要词语解释
    asp.net CROSS-PAGE POSTING
  • 原文地址:https://www.cnblogs.com/wxquare/p/5224995.html
Copyright © 2011-2022 走看看