首页 > 其他 > 详细

二叉树的先序+中序+后序的非递归遍历实现

时间:2021-02-04 21:02:30      阅读:38      评论:0      收藏:0      [点我收藏+]

写在开头:

  非递归同样需要用到栈结构去实现类似递归的这样一个操作,递归写法只不过很多步骤都由系统栈替我们完成,本质其实一样。

【先序】

【Code】

//先序遍历
    public static void xianxubianli(Node head)
    {
        if(head!=null)
        {
            Stack<Node> tool = new Stack<TreeProblem.Node>();
            tool.add(head);
            //当工具栈不为空时
            while(!tool.isEmpty())
            {
                //取出栈顶元素进行打印
                head = tool.pop();
                System.out.print(head.value+"    ");
                if(head.right!=null)
                    tool.push(head.right);
                if(head.left!=null)
                    tool.push(head.left);
            }
        }
    }

【中序】

//中序遍历
    public static void zhongxubianli(Node head)
    {
        if(head!=null)
        {
            Stack<Node>p = new Stack<TreeProblem.Node>();
            while(!p.isEmpty()||head!=null)
            {
                if(head!=null)
                {
                    p.push(head);
                    head=head.left;
                }
                    else {
                    head = p.pop();
                    System.out.print(head.value+"    ");
                    head = head.right;
                }
            }
        }
    }

【后序】

public static void houxubianli(Node head)
    {
        if(head!=null)
        {
            Stack<Node>p1 = new Stack<TreeProblem.Node>();
            Stack<Node>p2 = new Stack<TreeProblem.Node>();
            p1.push(head);
            while(!p1.isEmpty())
            {
                head = p1.pop();
                p2.push(head);
                if(head.left!=null)
                    p1.push(head.left);
                if(head.right!=null)
                    p1.push(head.right);
            }
            while(!p2.isEmpty())
            {
                System.out.print(p2.pop().value+"    ");
            }
        }
    }

 

二叉树的先序+中序+后序的非递归遍历实现

原文:https://www.cnblogs.com/pionice/p/14374629.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!