题目地址:https://leetcode.com/problems/binary-tree-level-order-traversal/
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
题目要求自顶向下地水平遍历二叉树,实现这个代码的关键点就是每次都要保存一层节点,在遍历一层节点的同时,再去保存这层节点的孩子节点,即下一层节点。把握住这一点,其实也就解决问题了。
public class BinaryTreeLevelOrderTraversal {
public static List<List<Integer>> levelOrder(TreeNode root) {
// 保存最终结果
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
// 保存没一层的节点
List<TreeNode> levelNodeList = new ArrayList<TreeNode>();
if (root == null)
return resultList;
else
levelNodeList.add(root);
while (!levelNodeList.isEmpty()) {
// 保存当前遍历节点的值
List<Integer> levelValList = new ArrayList<Integer>();
// 保存下一层的节点
List<TreeNode> childList = new ArrayList<TreeNode>();
for (TreeNode node : levelNodeList) {
levelValList.add(node.val);
if (node.left != null)
childList.add(node.left);
if (node.right != null)
childList.add(node.right);
}
resultList.add(levelValList);
levelNodeList.clear();
levelNodeList = childList;
}
return resultList;
}
public static void main(String[] args) {
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(6);
TreeNode node7 = new TreeNode(7);
node1.left = node2;
node1.right = node3;
node2.left = node4;
node2.right = node5;
node3.left = node6;
node3.right = node7;
BinaryTreeLevelOrderTraversal binaryTreeLevelOrderTraversal = new BinaryTreeLevelOrderTraversal();
System.out.println(binaryTreeLevelOrderTraversal.levelOrder(node1));
}
}