BFS+DFS

利用tree来做BFS和DFS。
在tree里,BFS和level-Order的遍历,而DFS和PreOrder是一样的
public class Graph {
	static int index = 0;
	public static void main(String[] args) {
		char[] str = {'a','b','c','#','#','d','e','#','g','#','#','f','#','#','h','i','#','#','j','#','#'};
		Node tree = null; 
		tree = CreateTree(str, tree);
		UnrecursiveDFS(tree);//unrecursive DFS = preorder
		System.out.println();
		
		tree = null; index = 0;
		tree = CreateTree(str, tree);
		RecursiveDFS(tree);//recursive DFS = recursive preorder
		System.out.println();
		
		tree = null; index = 0;
		tree = CreateTree(str, tree);
		UnrecursiveBFS(tree);//unrecursive BFS = level order 	
	}
	
	public static Node CreateTree(char[] str, Node tree){
		if(str[index] == '#'){
			tree = null;
			index++;
		}
		else{
			tree = new Node();
			tree.status = 0;
			tree.data = str[index]; index++;
			tree.lchild = CreateTree(str, tree.lchild);
			tree.rchild = CreateTree(str, tree.rchild);
		}
		return tree;
	}
	
	public static void RecursiveDFS(Node tree){
		if(tree == null)
			return;
		else if(tree.status == 0){
			System.out.print(tree.data+" ");
			tree.status = 2;
			RecursiveDFS(tree.lchild);
			RecursiveDFS(tree.rchild);
		}
	}
	
	public static void UnrecursiveDFS(Node tree){
        Stack<Node> stack = new Stack<Node>();  
        tree.status = 1;
        stack.add(tree);
        while(!stack.isEmpty()){
        	Node u = stack.pop();
        	if(u != null){
        		if(u.rchild != null && u.rchild.status == 0){
        			u.rchild.status = 1;
        			stack.add(u.rchild);
        		}
        		if(u.lchild != null && u.lchild.status == 0){
        			u.lchild.status = 1;
        			stack.add(u.lchild);
        		}
        		u.status = 2;
        		System.out.print(u.data+" ");
        	}
        }
	}
	
	public static void UnrecursiveBFS(Node tree){
		LinkedList<Node> queue = new LinkedList<Node>();
		tree.status = 1;
		queue.add(tree);
        while(!queue.isEmpty()){//
        	Node u = queue.removeFirst();
        	if(u != null){
        		if(u.lchild != null && u.lchild.status == 0){
        			u.lchild.status = 1;
        			queue.add(u.lchild);
        		}
        		if(u.rchild != null && u.rchild.status == 0){
        			u.rchild.status = 1;
        			queue.add(u.rchild);
        		}
        		u.status = 2;
        		System.out.print(u.data+" ");
        	}
        }
	}
}

你可能感兴趣的:(C++,c,F#,C#,J#)