代码改变世界

后序遍历二叉树-非递归实现

2018-01-22 22:22  Dirichlet  阅读(545)  评论(0编辑  收藏  举报

用栈实现非递归后序遍历二叉树

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication8
{
    class TreeNode
    {
        public TreeNode(string name, TreeNode right, TreeNode left)
        {
            this.Name = name;
            this.Left = left;
            this.Right = right;
        }

        public TreeNode Left { get; set; }

        public TreeNode Right { get; set; }

        public bool IsVisited { get; set; }

        public string Name { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            /*
            1
         |        |
         2        3
       |   |    |   |
      4    7    5   6
         |   |
         8   9
            */
            List<TreeNode> nodeList = new List<TreeNode>();

            for (int i = 1; i <= 9; i++)
            {
                nodeList.Add(new TreeNode($"{i} ", null, null));
            }

            nodeList[0].Left = nodeList[1];
            nodeList[0].Right = nodeList[2];
            nodeList[1].Left = nodeList[3];
            nodeList[1].Right = nodeList[6];
            nodeList[2].Left = nodeList[4];
            nodeList[2].Right = nodeList[5];
            nodeList[6].Left = nodeList[7];
            nodeList[6].Right = nodeList[8];

            Recurse(nodeList[0]);
        }

        static void Recurse(TreeNode node)
        {
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.Push(node);

            while (stack.Count > 0)
            {
                var top = stack.Peek();

                if ((top.Right == null && top.Left == null) ||
                    ((top.Left == null || top.Left.IsVisited == true) &&
                    (top.Right == null || top.Right.IsVisited == true))
                    )
                {
                    top = stack.Pop();
                    Console.Write(top.Name);
                    top.IsVisited = true;
                    continue;
                }

                if (top.Right != null)
                {
                    stack.Push(top.Right);
                }

                if (top.Left != null)
                {
                    stack.Push(top.Left);
                }
            }
        }
    }
}

 

结果:

4 8 9 7 2 5 6 3 1