劍指offer-面試題54:二叉搜索樹的第K大節點

題目描述

給定一棵二叉搜索樹,請找出其中的第k小的結點。例如, (5,3,7,2,4,6,8)    中,按結點數值大小順序第三小結點的值爲4。

解法一:

中序遍歷遞歸

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

    }
    
};

解法二:

中序遍歷非遞歸

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
       return  Inorder(pRoot, k);
    }
    
    TreeNode* Inorder(TreeNode* &pRoot, int &k)
    {
        int count = 0;
        TreeNode* p = pRoot;
        stack<TreeNode* >st;
        while(!st.empty() || p!=NULL)
        {
            while(p)
            {
                st.push(p);
                p = p->left;;
            }
            p = st.top();
            count++;
            if(count==k)
                return p;
            st.pop();
            p = p->right;
        }
        return NULL;
    }
    
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章