劍指 二叉搜索樹的第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)
    {
        TreeNode* tmp = pRoot;
        if(pRoot == NULL) return NULL;
        stack<TreeNode*> q;
        while(tmp != NULL || !q.empty()) {
            if(tmp != NULL) {
                q.push(tmp);
                tmp = tmp->left;
            }
            else {
                TreeNode* top = q.top();
                q.pop();
                k--;
                if(k == 0) return top;
                tmp = top->right;
            }
        }
        return tmp; 

    }

    
};

 

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