C++ 递归与非递归方式实现中序遍历

二叉搜索树的第k个结点

http://www.nowcoder.com/questionTerminal/ef068f602dde4d28aab2b210e859150a

用stack实现中序遍历

   TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(pRoot == nullptr || k <= 0)
        {
            return nullptr;
        }
        vector<TreeNode*> vec;
        stack<TreeNode*> sta;
        TreeNode* pNode = pRoot;
        while(pNode != nullptr || !sta.empty())
        {
            while(pNode != nullptr)
            {
                sta.push(pNode);
                pNode = pNode->left;
            }
            if(!sta.empty())
            {
                pNode = sta.top();
                sta.pop();
                vec.push_back(pNode);
                pNode = pNode->right;
            }
        }
        int length = vec.size();
        if(k <= length)
        {
           return vec[k - 1];
        }
        return nullptr;

非递归方式(stack)实现

TreeNode* KthNode(TreeNode* pRoot, int k)
    {
        if(pRoot == nullptr || k <= 0)
        {
            return nullptr;
        }
        vector<TreeNode*> vec;
        stack<TreeNode*> sta;
        TreeNode* pNode = pRoot;
        while(pNode != nullptr || !sta.empty())
        {
            while(pNode != nullptr)
            {
                sta.push(pNode);
                pNode = pNode->left;
            }
            if(!sta.empty())
            {
                pNode = sta.top();
                sta.pop();
                vec.push_back(pNode);
                pNode = pNode->right;
            }
        }
        int length = vec.size();
        if(k <= length)
        {
           return vec[k - 1];
        }
        return nullptr;
    }
全部评论

相关推荐

双尔:反手回一个很抱歉,经过慎重考虑,您与我的预期暂不匹配,感谢您的投递
点赞 评论 收藏
分享
Jcwemz:中软证书写单行,考了什么学了什么相关技术栈的内容就说自己会什么, 没实习就包装实习简历,将项目经历写成实习做的,项目时间拉长,项目成果具体化,测试的项目成果无非就是写了多少用例查出了多少bug,重要的不是实习了多久,而是你会多少东西,你能表达的就都是你的。 cet4,随便找个地方标上就好了,不用写单行。 粗略建议,我也不在行,觉得对的可以采纳
实习,投递多份简历没人回...
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务