Exemplo n.º 1
0
        public void TraverseInOrderNonRecursive()
        {
            if (Root != null)
            {
                Stack stack = new Stack(this.Count);
                var root = Root;
                while (true)
                {
                    while (root != null)
                    {
                        stack.Push(root);
                        root = root.Left;
                    }

                    if (stack.Size > 0)
                    {
                        root = (BinaryTreeNode)stack.Pop();
                        Console.WriteLine(root.Value);
                        root = root.Right;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
Exemplo n.º 2
0
        public void TraversePostOrderNonRecursive()
        {
            if (Root != null)
            {
                Stack stack = new Stack(this.Count);
                var root = Root;
                while (true)
                {
                    if (root != null)
                    {
                        stack.Push(root);
                        root = root.Left;
                    }

                    else
                    {
                        if (stack.Size > 0)
                        {

                            if (((BinaryTreeNode)stack.Top()).Right == null)
                            {
                                root = (BinaryTreeNode)stack.Pop();
                                Console.WriteLine(root.Value);

                                var top = (BinaryTreeNode)stack.Top();
                                if (root.Value == top.Right.Value)
                                {
                                    Console.WriteLine(top.Value);
                                    stack.Pop();
                                }

                                if (stack.Size > 0)
                                    root = ((BinaryTreeNode)stack.Top()).Right;
                            }
                            else
                            {
                                root = null;
                            }
                        }
                        else
                        {
                            return;
                        }
                    }

                }
            }
        }