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;
    }
全部评论

相关推荐

敢逐云霄志:你打招呼语怎么能这么长,hr都没看下去的欲望,简明扼要说重点,就读于某某学校某某专业,26届应届毕业生,学信网可查,先后在某某公司实习过(如有),然后做过什么项目,想找一份什么样的工作,可实习几个月以上,期待您的回复。
点赞 评论 收藏
分享
Java面试先知:我也是和你一样的情况,hr 说等开奖就行了
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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