1. 程式人生 > >二叉搜索樹的第k個結點

二叉搜索樹的第k個結點

二叉搜索樹 題目 null bsp style 結點 turn title 數值

題目描述

給定一顆二叉搜索樹,請找出其中的第k小的結點。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按結點數值大小順序第三個結點的值為4。 思路:二叉搜索樹就是二叉排序樹,也叫二叉查找樹。 其中序遍歷就是順序的。 我的代碼:
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(pRoot == NULL || k == 0)
            return NULL;
        return KthNodeCore(pRoot,k);
    }
    TreeNode* KthNodeCore(TreeNode* pRoot , int
& k) { TreeNode* target = NULL; if(pRoot->left) { target = KthNodeCore(pRoot->left , k); } if(target == NULL) { if(k == 1) target = pRoot; k--; } if(target == NULL && pRoot->right) target
= KthNodeCore(pRoot->right , k); return target; }

二叉搜索樹的第k個結點