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

    https://www.cnblogs.com/grandyang/p/4620012.html

    这个题其实就是中序遍历第k个数就好了,代码最好写的就是非递归的方式,在stack里面找第k个就好了。也可以使用递归的方式:

    class Solution {
    public:
        int kthSmallest(TreeNode* root, int k) {
            return Smallest(root,k);
        }
        int Smallest(TreeNode* root,int& k){
            if(root == NULL)
                return -1;
            int num = Smallest(root->left,k);
            if(k == 0)
                return num;
            if(--k == 0)
                return root->val;
            return Smallest(root->right,k);
        }
    };

    注意:这种递归的方法在NULL时候返回-1,如果找到了数字,返回值就会以当前的结果替代-1.

    另一种写法:

    自己写的

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int kthSmallest(TreeNode* root, int k) {
            int index = 0,num = -1;
            kthSmallest(root,k,index,num);
            return num;
        }
        void kthSmallest(TreeNode* root,int k,int& index,int& num){
            if(!root)
                return;
            kthSmallest(root->left,k,index,num);
            index++;
            if(index == k){
                num = root->val;
                return;
            }
            kthSmallest(root->right,k,index,num);
        }
    };
  • 相关阅读:
    443. String Compression
    506. Relative Ranks
    825. Friends Of Appropriate Ages
    447. Number of Boomerangs
    54. Spiral Matrix
    744. Find Smallest Letter Greater Than Target
    HDU-1565 方格取数(1)
    zoj 3672 Gao The Sequence
    ZOJ 3675 Trim the Nails
    poj -2955 Brackets
  • 原文地址:https://www.cnblogs.com/ymjyqsx/p/10675805.html
Copyright © 2011-2022 走看看