要求:
按顺序打印树结构
按顺序打印 1,2,3,4,5(不考虑值在树中的准确性)
解法
- 树的类
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
- 实现
public static void levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>() {{
add(root);
}};
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
System.out.println(node.val);
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
}
- 测试
public static void main(String[] args)
TreeNode treeNode = new TreeNode(1);
treeNode.left = new TreeNode(2);
TreeNode rig = new TreeNode(3);
rig.left = new TreeNode(4);
rig.right = new TreeNode(5);
treeNode.right = rig;
levelOrder(treeNode); // 1,2,3,4,5
}