代码功能
这段Java代码定义了一个二叉树,并实现了两种遍历方法:深度优先搜索(DFS)和广度优先搜索(BFS)。通过DFS,代码从根节点开始,优先访问子节点,直至最深的节点;通过BFS,代码从根节点开始,逐层访问所有节点。最终,代码在控制台打印出两种遍历的节点值序列。
代码
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
// 定义二叉树节点类
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public class BinaryTree {
TreeNode root;
// 构建二叉树
public BinaryTree() {
root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
}
// 深度优先搜索(前序遍历)
public void depthFirstSearch(TreeNode node) {
if (node == null) {
return;
}
System.out.print(node.val + " ");
depthFirstSearch(node.left);
depthFirstSearch(node.right);
}
// 广度优先搜索
public void breadthFirstSearch(TreeNode node) {
if (node == null) {
return;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(node);
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
System.out.print(current.val + " ");
if (current.left != null) {
queue.add(current.left);
}
if (current.right != null) {
queue.add(current.right);
}
}
}
public static void main(String[] args) {
BinaryTree tree = new BinaryTree();
System.out.println("深度优先搜索(前序遍历)输出:");
tree.depthFirstSearch(tree.root);
System.out.println();
System.out.println("广度优先搜索输出:");
tree.breadthFirstSearch(tree.root);
}
}