题解 | #二叉搜索树与双向链表#

二叉搜索树与双向链表

http://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5

//中序遍历 + 非递归 
class Solution {
public:
    TreeNode* Convert(TreeNode* root) {
        stack<TreeNode*> st;
        TreeNode *last_visit=nullptr, *ans=nullptr;
        while(!st.empty() || root)
        {
            while(root)
            {
                st.push(root);
                root = root->left;
            }
            root = st.top();
            st.pop();
            if(last_visit == nullptr) 
            {
                ans = root;
            }
            else
            {
                root->left = last_visit;
                last_visit->right = root;
            }
            last_visit = root;
            root = root->right;
        }
        return ans;
    }
};
//中序遍历 + 递归(全局变量)
class Solution {
public:
    TreeNode* Convert(TreeNode* root) {
        if(!root) return nullptr;
        Convert(root->left);
        if(last_visit == nullptr)
        {
            ans = root;
        }
        else
        {
            root->left = last_visit;
            last_visit->right = root;
        }
        last_visit = root;
        Convert(root->right);
        return ans;
    }
private:
    TreeNode *ans=nullptr, *last_visit=nullptr;
};
全部评论

相关推荐

ResourceUt...:楼主有自己的垃圾箱,公司也有自己的人才库
点赞 评论 收藏
分享
10-10 01:10
已编辑
深圳大学 测试开发
面了100年面试不知...:六月到九月,四个项目一个实习,是魔丸吗
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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