二叉树 Morris 遍历 前中后序遍历

    /**
     *    1
     *  2   3
     * 4 5 6 7
     * 遍历 
     * 1 将5 右节点设为1
     * 2 将4 右节点设为2
     * 4 无左节点 将下次节点设为4的右节点 就是2
     * 2 左节点的最右边一个节点的右节点 是当前节点2, 还原该节点 设为null,下个节点设为2的右节点5
     * 5 无左节点 将下次节点设为5的右节点 就是1
     * 1 左节点的最右边一个节点5的右节点 是当前节点1, 还原该节点 设为null,下个节点设为1的右节点3
     * 后面类似上面步骤
     */
    public static void Morris(TreeNode root)
    {
        if (root == null) return;
        TreeNode pre = null;
        TreeNode cur = root;
        List<int> before = new List<int>();
        List<int> middle = new List<int>();
        List<int> after = new List<int>();
        while (cur != null)
        {
            pre = cur.left;
            if (pre != null)
            {
                while (pre.right != null && pre.right != cur)
                    pre = pre.right;
                if (pre.right == null)
                {
                    before.Add(cur.val);
                    pre.right = cur;
                    cur = cur.left;
                }
                else
                {
                    middle.Add(cur.val);
                    pre.right = null;
                    AfterPath(after, cur.left);
                    cur = cur.right;
                }
            }
            else
            {
                before.Add(cur.val);
                middle.Add(cur.val);
                cur = cur.right;
            }
        }
        AfterPath(after, root);// 将最右边一列放到遍历列表内
        Console.WriteLine("先序:" + string.Join(",", before));
        Console.WriteLine("中序:" + string.Join(",", middle));
        Console.WriteLine("后序:" + string.Join(",", after));
    }

    private static void AfterPath(List<int> list,TreeNode node)
    {
        int count = 0;
        while (node != null)
        {
            list.Add(node.val);
            node = node.right;
            count++;
        }
        int left = list.Count - count;
        int right = list.Count - 1;
        int temp;
        while (left < right)
        {
            temp = list[left];
            list[left] = list[right];
            list[right] = temp;
            left++;
            right--;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值