首页 > 其他 > 详细

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

时间:2020-02-23 22:32:36      阅读:78      评论:0      收藏:0      [点我收藏+]
package MyExc;

import java.util.Stack;

class TreeNode{
    int data;
    TreeNode left;
    TreeNode right;
}


public class BinaryTree {
    public void preOrder(TreeNode head){
        Stack<TreeNode> stack = new Stack<>();
        stack.add(head);
        while(!stack.isEmpty()){
            head=stack.pop();
            System.out.println(head.data);
            if(head.right==null){
                stack.push(head.right);
            }
            if(head.left==null){
                stack.push(head.left);
            }
        }
    }

    public void inOrder(TreeNode head){
        Stack<TreeNode> stack = new Stack<>();
        //只要不为空,一直往左走
        if(head!=null){
            head=head.left;
        }else{//为空,弹出一个,然后向右走一步
            head=stack.pop();
            System.out.println(head.data);
            head = head.right;
        }
    }

    public void postOrder(TreeNode head){
        Stack<TreeNode> stack = new Stack<>();
        Stack<TreeNode> help = new Stack<>();
        stack.push(head);

        while (!stack.isEmpty()){
            head = stack.pop();
            help.push(head);
            if(head.left!=null){
                stack.push(head.left);
            }
            if(head.right!=null){
                stack.push(head.right);
            }
            while (!help.isEmpty()){
                System.out.println(help.pop().data);
            }
        }
    }
}

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

原文:https://www.cnblogs.com/kristse/p/BinaryTree.html

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