剑指offer 面试题54 二叉搜索树的第K大节点

问题:给定一棵二叉搜索树,请找出其中第k大的节点。

思路:中序遍历

代码:

Recursion

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    TreeNode* res=nullptr;
    void inOrder(TreeNode* pRoot,int& k)
    {
        if(pRoot==nullptr)
            return;
        if(pRoot->left)
            inOrder(pRoot->left,k);
        if(!(--k))
            res=pRoot;
        if(pRoot->right)
            inOrder(pRoot->right,k);
    }
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(pRoot==nullptr||k==0)
            return nullptr;
        inOrder(pRoot,k);
        return res;
    }
};

Iteration

/**
 * 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) {
        stack<TreeNode*> sk;
        TreeNode* cur=root;
        while(!sk.empty()||cur)
        {
            while(cur)
            {
                sk.push(cur);
                cur=cur->left;
            }
            cur=sk.top();
            sk.pop();
            k--;
            if(k==0)
                return cur->val;
            cur=cur->right;
        }
        return 0;
    }
};

 复杂度分析:Recursion时间复杂度为O(n),空间复杂度为O(1). Iteration 时间复杂度为O(k) ,空间复杂度为O(h+k).

 
发布了115 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_22148493/article/details/105168063