The sword refers to the Kth node of the binary search tree

topic link

Non-recursive approach:

/*
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; 

    }

    
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326546413&siteId=291194637