二叉树的非递归遍历——java实现

import tree.Tree;
public class Main {
    public static void main(String[] args) {
        Tree left = new Tree(2,null,null);
        Tree right = new Tree(3,null,null);
        Tree head = new Tree(1,left,right);

        System.out.println("inorder_traverse:");
        head.inorder_traverse(head);
        System.out.println();

        System.out.println("inorder_traverse_norecursive:");
        head.inorder_traverse_norecursive(head);
        System.out.println();

        System.out.println("preorder_traverse_norecursive:");
        head.preorder_traverse_norecursive(head);
        System.out.println();

        System.out.println("laorder_traverse_norecursive:");
        head.laorder_traverse_norecursive(head);
        System.out.println();


    }
}

package tree;

import java.util.Stack;

public class Tree {
    public int value;
    public Tree left;
    public Tree right;

    public Tree(int value, Tree left, Tree right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }

    public void do_something(Tree node) {
        System.out.print(node.value);
    }

    public void inorder_traverse(Tree node) {
        if(node.left != null) {
            this.inorder_traverse(node.left);
        }
        do_something(node);
        if(node.right != null) {
            this.inorder_traverse(node.right);
        }
    }

    public void inorder_traverse_norecursive(Tree node) {
        Stack stack = new Stack();

        do {
            while(node != null) {
                stack.push(node);
                node = node.left;
            }

            if(!stack.empty()) {
                Tree top = stack.pop();
                do_something(top);

                if(top.right != null) {
                    node = top.right;
                }
            }

        }while (!stack.empty() || node != null);
    }

    public void preorder_traverse_norecursive(Tree node) {
        Stack stack = new Stack();

        do{
            while (node != null) {
                do_something(node);
                stack.push(node);
                node = node.left;
            }
            if(!stack.empty()) {
                Tree top = stack.pop();
                if(top.right != null) {
                    node = top.right;
                }
            }
        }while (!stack.empty() || node != null);
    }

    public void laorder_traverse_norecursive(Tree node) {
        Stack stack = new Stack();
        do {
            while (node != null) {
                stack.push(node);
                node = node.left;
            }

            if (!stack.empty()) {
                Tree top = stack.pop();
                if(top.right != null) {
                    node = top.right;
                }
                do_something(top);
            }

        }while (!stack.empty() || node != null);
    }
}

你可能感兴趣的:(数据结构)