Binary Tree Inorder Traversal [leetcode] 非递归的三种解法

第一种方法是Morris Traversal

是O(n)时间复杂度,且不需要额外空间的方法。缺点是需要修改树。

通过将叶子节点的right指向其中序后继。

代码如下

    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> res;
        TreeNode * cur = root;
        TreeNode * pre = NULL;
        while (cur)
        {
            if (cur->left == NULL)
            {
                res.push_back(cur->val);
                cur = cur->right;
            }
            else
            {
                pre = cur->left;
                while (pre->right && pre->right != cur) pre = pre->right;
            
                if (pre->right == NULL)
                {
                    pre->right = cur;
                    cur = cur->left;
                }
                if (pre->right == cur)
                {
                    pre->right = NULL;
                    res.push_back(cur->val);
                    cur = cur->right;
                }
            }
        }
        return res;
    }

第二种方法利用栈,模拟递归过程

    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> res;
        vector<TreeNode*> stack;
        stack.push_back(root);
        set<TreeNode*> visited;
        while (stack.size())
        {
            TreeNode * cur = stack.back();
            stack.pop_back();
            if (!cur) continue;
            if (visited.find(cur) == visited.end())//visited for the first time
            {
                stack.push_back(cur->right);
                stack.push_back(cur);
                stack.push_back(cur->left);
                visited.insert(cur);
            }
            else//visited for the second time
                res.push_back(cur->val);
        }
        return res;
    }


第三种方法来自《数据结构》

将所有左子节点入栈,当没有左子结点时取栈顶元素打印并转移到右子节点

    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> res;
        vector<TreeNode*> stack;
        TreeNode* cur = root;
        while (stack.size() || cur)
        {
            if (cur)
            {
                stack.push_back(cur);
                cur = cur->left;
            }
            else
            {
                cur = stack.back();
                stack.pop_back();
                res.push_back(cur->val);
                cur = cur->right;
            }
        }
        return res;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值