剑指Offer——JZ62.二叉搜索树的第k个结点【中序遍历】

题目传送门


在这里插入图片描述


题解

  • 中序遍历记格数即可

AC-Code

/*
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) {
        if(pRoot == NULL)    return NULL;
        int num = 0;
        stack<TreeNode*> st;
        TreeNode * p = pRoot;
        while(p != NULL || !st.empty()) {
            while(p != NULL) {
                st.push(p);
                p = p->left;
            }
            if(!st.empty()) {
                p = st.top();
                st.pop();
                ++num;
                if(num == k)    return p;
                p = p->right;
            }
        }
        return NULL;
    }    
};

猜你喜欢

转载自blog.csdn.net/Q_1849805767/article/details/106729388