【剑指offer】二叉查找树中第k小的节点

题目描述

给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。

题解:

非递归中序遍历方式, 并计数

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

递归方式

class Solution {
public:
    int count =0;
    TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(pRoot){ 
            TreeNode *ret = KthNode(pRoot->left, k);
            if(ret) return ret;
            if(++count == k) return pRoot;
            ret = KthNode(pRoot->right,k);
            if(ret) return ret;
        }
        return NULL;
    }
};

你可能感兴趣的:(牛客算法题)