二叉樹的非遞迴遍歷——java實現

塵埃092發表於2015-03-24
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<Tree> stack = new Stack<Tree>();

        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<Tree> stack = new Stack<Tree>();

        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<Tree> stack = new Stack<Tree>();
        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);
    }
}

相關文章