思路文章参考
Java实现深度优先遍历和广度优先遍历
代码
深度遍历(DFS)
package tree;
import java.util.Stack;
public class DFSIterator implements IteratorMethodBase {
public void doIterator(Node node) {
if(node == null) {
return;
}
Stack<Node> nodeStack = new Stack<>();
nodeStack.push(node);
System.out.println("深度优先遍历结果为:");
while(nodeStack.size() > 0) {
node = nodeStack.pop();
if(node == null) {
continue;
}
System.out.print(node.getData()+" ");
if(node.getRightNode() != null) {
nodeStack.push(node.getRightNode());
}
if(node.getLeftNode() != null) {
nodeStack.push(node.getLeftNode());
}
}
}
}
广度遍历(BFS)
package tree;
import java.util.LinkedList;
import java.util.Queue;
public class BFSIterator implements IteratorMethodBase {
public void doIterator(Node node) {
if(node == null) {
return;
}
Queue<Node> nodeQueue = new LinkedList<>();
nodeQueue.add(node);
System.out.println("广度优先遍历结果为:");
while(nodeQueue.size() > 0) {
node = nodeQueue.poll();
if(node == null) {
continue;
}
System.out.print(node.getData() + " ");
if(node.getLeftNode()!= null) {
nodeQueue.add(node.getLeftNode());
}
if(node.getRightNode() != null) {
nodeQueue.add(node.getRightNode());
}
}
}
}
Node类
package tree;
public class Node {
private int data;
private Node leftNode;
private Node rightNode;
public Node(int data, Node leftNode, Node rightNode) {
this.data = data;
this.leftNode = leftNode;
this.rightNode = rightNode;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeftNode() {
return leftNode;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}
public Node getRightNode() {
return rightNode;
}
public void setRightNode(Node rightNode) {
this.rightNode = rightNode;
}
}
遍历方法接口
package tree;
public interface IteratorMethodBase {
public void doIterator(Node node);
}
main方法类
package tree;
public class TestMain {
public static void main(String[] args) {
IteratorMethodBase methodBase = createIteratorMethod("BFS");
methodBase.doIterator(initTree());
}
public static Node initTree() {
Node node4 = new Node(4, null, null);
Node node5 = new Node(5, null, null);
Node node6 = new Node(6, null, null);
Node node7 = new Node(7, null, null);
Node node2 = new Node(2, node4, node5);
Node node3 = new Node(3, node6, node7);
Node node = new Node(1, node2, node3);
return node;
}
public static IteratorMethodBase createIteratorMethod(String type) {
if("BFS".equals(type)) {
return new BFSIterator();
} else if("DFS".equals(type)) {
return new DFSIterator();
} else {
return null;
}
}
}