广度优先遍历类似于二叉树的层序遍历。采用队列的形式实现。
public class BFS {
public List<Integer> bfs(BinaryTreeNode root) {
ArrayList<Integer> lists = new ArrayList<>();
if (root == null) {
return lists;
}
Queue<BinaryTreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
BinaryTreeNode treeNode = queue.poll();
if (treeNode.getLeft() != null) {
queue.offer(treeNode.getLeft());
}
if (treeNode.getRight() != null) {
queue.offer(treeNode.getRight());
}
lists.add(treeNode.getData());
}
return lists;
}
}
深度优先遍历类似于树的先序遍历,使用栈来实现。
public class DFS {
// 非递归实现
public List<Integer> dfs(BinaryTreeNode root) {
List<Integer> lists = new ArrayList<>();
if (root == null) {
return lists;
}
Stack<BinaryTreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
BinaryTreeNode treeNode = stack.pop();
if (treeNode.getRight() != null) {
stack.push(treeNode);
}
if (treeNode.getLeft() != null) {
stack.push(treeNode);
}
lists.add(treeNode.getData());
}
return lists;
}
// 递归实现
public void dfsTraversal(BinaryTreeNode root) {
if (root != null) {
System.out.println(root.getData() + " ");
dfsTraversal(root.getLeft());
dfsTraversal(root.getRight());
}
}
}