前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >二叉树后序遍历-非递归版

二叉树后序遍历-非递归版

作者头像
名字是乱打的
发布2022-05-13 09:58:05
1810
发布2022-05-13 09:58:05
举报
文章被收录于专栏:软件工程

后续遍历跟先序遍历比较像,这里是定义了两个栈,把打印的先放在打印栈stack2里

代码语言:javascript
复制
package com.algorithm.practice.tree.traversal;

import java.util.Stack;

public class PosOrderPrint {

    public static class Node {
        public int value;
        public Node left;
        public Node right;

        public Node(int data) {
            this.value = data;
        }
    }

    public static void  posOrderPrint(Node head){
        System.out.print("postnatal-order: ");
        if (head!=null){
            Stack<Node> stack1=new Stack<>();
            Stack<Node> stack2=new Stack<>();
            stack1.push(head);
            while (!stack1.isEmpty()){
                head = stack1.pop();
                stack2.push(head);
                if (head.left!=null){
                    stack1.push(head.left);
                }
                if (head.right!=null){
                    stack1.push(head.right);
                }
            }
            while (!stack2.isEmpty())
            {
                System.out.print(stack2.pop().value+" ");
            }
        }
    }

    public static void main(String[] args){
        Node head = new Node(5);
        head.left = new Node(3);
        head.right = new Node(8);
        head.left.left = new Node(2);
        head.left.right = new Node(4);
        head.left.left.left = new Node(1);
        head.right.left = new Node(7);
        head.right.left.left = new Node(6);
        head.right.right = new Node(10);
        head.right.right.left = new Node(9);
        head.right.right.right = new Node(11);
        posOrderPrint(head);
        System.out.println();
    }


}
代码语言:javascript
复制
public static void posOrderUnRecur2(Node h) {
        System.out.print("pos-order: ");
        if (h != null) {
            Stack<Node> stack = new Stack<Node>();
            stack.push(h);
            Node c = null;
            while (!stack.isEmpty()) {
                c = stack.peek();
                if (c.left != null && h != c.left && h != c.right) {
                    stack.push(c.left);
                } else if (c.right != null && h != c.right) {
                    stack.push(c.right);
                } else {
                    System.out.print(stack.pop().value + " ");
                    h = c;
                }
            }
        }
        System.out.println();
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档