zoukankan      html  css  js  c++  java
  • 二叉树前中后序遍历非递归实现

    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);
                }
            }
        }
    }
    
  • 相关阅读:
    第07组 Alpha冲刺(1/6)
    第07组 团队Git现场编程实战
    第07组 团队项目-需求分析报告
    团队项目-选题报告
    第二次结对编程作业
    0012---求滑动距离
    0011---绝对值函数
    0010---温度转换
    0009---乘法问题
    0008---三位数倒序问题
  • 原文地址:https://www.cnblogs.com/kristse/p/BinaryTree.html
Copyright © 2011-2022 走看看