二叉树 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--;
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_42235716/article/details/128299686
今日推荐