不用递归方法的树的遍历

package src2;

import java.util.Stack;

public class BuildTree {

    static class Node {
        public char val;
        public Node left;
        public Node right;

        public Node(char val) {
            this.val = val;
        }
    }


    static Node build() {
        Node A = new Node('A');
        Node B = new Node('B');
        Node C = new Node('C');
        Node D = new Node('D');
        Node E = new Node('E');
        Node F = new Node('F');
        Node G = new Node('G');
        Node H = new Node('H');
        Node I = new Node('I');

        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        D.left = G;
        D.right = H;
        C.left = F;
        F.right = I;

        return A;
    }

    //先序遍历,不用递归,
    //用栈来储存对象
    public static void perOrder(Node root) {
        if(root == null) {
            return;
        }

        Stack<Node> stack = new Stack<>();

        stack.push(root);
        while(!stack.isEmpty()) {
            Node A = stack.pop();
            System.out.print(A.val + " ");
            if(A.right != null) {
                //将右子树先放入栈
                //那木最后访问右子树
                stack.push(A.right);
            }
            if(A.left != null) {
                stack.push(A.left);
            }
        }
    }

    //中序遍历
    public static void inOrder(Node root) {

        if(root == null) {
            return;
        }

        Stack<Node> stack = new Stack<>();
        Node cur = root;

        while(true) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }

            if(stack.empty()) {
                break;
            }
            Node top = stack.pop();
            System.out.print(top.val + " ");

            cur = top.right;
        }

    }

    //后序遍历
    public static void postOrder(Node root) {
        if(root == null) {
            return;
        }

        Stack<Node> stack = new Stack<>();

        Node cur = root;
        Node prev = null;//来记录上一个被访问过的节点
        while(true) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }

            if(stack.isEmpty()) {
                break;
            }

            Node top = stack.peek();

            if(top.right  == null || top.right == prev) {
                System.out.print(top.val + " ");
                stack.pop();
                prev = top;//保存被访问的节点
            } else {
                cur = top.right;
            }

        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值