【劍指offer】題63:二叉搜索樹的第k個節點


TreeNode* KthNode_core(TreeNode* pRoot, int& k)
{
    TreeNode* target(NULL);
    if (pRoot->left!=NULL)
    {
        target = KthNode_core(pRoot->left, k);
    }
    if (target == NULL)
    {
        k--;
        if (k == 0)
        {
            target = pRoot;
        }
    }
    if (target == NULL && pRoot->right!=NULL)
    {
        target = KthNode_core(pRoot->right, k);
    }
    return target;
}

TreeNode* KthNode(TreeNode* pRoot, int k)
{
    if (pRoot == NULL)
    {
        return pRoot;
    }
    return KthNode_core(pRoot, k);
}

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