import java.util.*;/*** 类功能描述: 二叉树遍历算法Java实现
*
*@version1.0.0
* @auther Create by Barry
* @date Create on 2018/3/12.
* @history*/
public classBinaryTree {privateNode root;privateBinaryTree(Object data){this.root = new Node(data, null, null);
}/*** 1、 深度优先遍历
* 1.1 递归先序遍历*/
public voidpreOrderTraverse(Node root){
System.out.println(root.data);
preOrderTraverse(root.leftChild);
preOrderTraverse(root.rightChild);
}/*** 1、 深度优先遍历
* 1.2 实现非递归先序遍历*/
public voidpreOrder(){
Stack stack= newStack();
System.out.println(root.data);
stack.push(root);while(!stack.isEmpty()){
Node element=(Node)stack.pop();
System.out.println(element.data);if(element.rightChild != null){
stack.push(element.rightChild);
}if(element.leftChild != null){
stack.push(element.leftChild);
}
}
}/*** 2、 广度优先遍历*/
public ListbreadthTraverse(Node root){
List allNodes = new LinkedList<>();if(root == null){returnallNodes;
}
Deque queue = new ArrayDeque<>();
queue.add(root);while(!queue.isEmpty()){
Node currentNode=queue.poll();
allNodes.add(currentNode);if(currentNode.leftChild != null){
queue.add(currentNode.leftChild);
}if(currentNode.rightChild != null){
queue.add(currentNode.rightChild);
}
}returnallNodes;
}classNode{privateObject data;privateNode leftChild;privateNode rightChild;publicNode(Object data, Node leftChild, Node rightChild){this.data =data;this.leftChild =leftChild;this.rightChild =rightChild;
}
}
}