树的遍历分两种:
1、深度优先遍历
1.1 递归算法实现
2.2 非递归算法实现(使用栈存储)
2、广度优先遍历(使用队列存储)
import java.util.*;
/**
* 类功能描述: 二叉树遍历算法Java实现
*
* @version 1.0.0
* @auther Create by Barry
* @date Create on 2018/3/12.
* @history
*/
public class BinaryTree {
private Node root;
private BinaryTree(Object data){
this.root = new Node(data, null, null);
}
/**
* 1、 深度优先遍历
* 1.1 递归先序遍历
*/
public void preOrderTraverse(Node root){
System.out.println(root.data);
preOrderTraverse(root.leftChild);
preOrderTraverse(root.rightChild);
}
/**
* 1、 深度优先遍历
* 1.2 实现非递归先序遍历
*/
public void preOrder(){
Stack stack = new Stack();
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 List<Node> breadthTraverse(Node root){
List<Node> allNodes = new LinkedList<>();
if(root == null){
return allNodes;
}
Deque<Node> 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);
}
}
return allNodes;
}
class Node{
private Object data;
private Node leftChild;
private Node rightChild;
public Node(Object data, Node leftChild, Node rightChild){
this.data = data;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
}
}