1. 程式人生 > >求一個二叉搜尋樹中第K個最小值

求一個二叉搜尋樹中第K個最小值

假設該顆二叉搜尋樹的總元素數大於等於K

解題思路:用STL容器的棧來實現

int kthSmallest(TreeNode* root, int k)
{

    std::stack<TreeNode*> Stack;
    while (root || !Stack.empty())
    {
        if (root)
        {
            Stack.push(root);
            root = root->left;
        }
        else
        {
            root = Stack.top();
            Stack.pop();
            if (--k == 0)
                return root->val;
            root = root->right;
        }
    }
}