中序遍历二叉树+O(1)空间

35 篇文章 0 订阅
24 篇文章 0 订阅

问题描述

中序遍历二叉树时,很简单,需要加上递归就可以优雅地实现了。当然,使用递归的话,函数调用栈的空间就会达到O(log n)。那么有什么方式,可以使得中序遍历二叉树的复杂度为O(1)呢?

问题分析

既然要保证O(1)复杂度,那么就不能使用递归调用了。目标方案应该是使用whilefor循环的方式。下面借用一张图来解释(来源:http://www.2cto.com/kf/201402/277873.html):
这里写图片描述

如图所示,需要在多个节点(right指针为空),设置指针指向父节点。这样在遍历的时候,就可以依靠这个指针来返回父节点了。在遍历完后,这些辅助指针会被撤去。

解决方案

这里直接用代码表示出来:

class TreeNode {                                                                
public:                                                                         
    int val;                                                                    
    TreeNode *left, *right;                                                     
    TreeNode(int val) {                                                         
        this->val = val;                                                        
        this->left = this->right = NULL;                                        
    }                                                                           
};     
    void inorderConstSpace(TreeNode *root) {
        while (root != NULL) {
            // if left child is NULL, then just visit root and continue
            if (root->left == NULL) {
                printf("%d\n", root->val);
                root = root->right;
                continue;
            }
            // find preceding node
            TreeNode *pre = NULL;
            for (pre = root->left; pre->right != root && pre->right != NULL; 
                    pre = pre->right) {}
            // if the preceding node is visited for the first time
            if (pre->right == NULL) {
                pre->right = root;
                root = root->left;
            } else {
                // preceding node is visited for the second time
                printf("%d\n", root->val);
                root = root->right;
                pre->right == NULL;
            }
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值