题目:(vivo面试)
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
题解:
import java.util.*;
class TreeNode {
int val;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
//层序遍历用队列
//边界条件
List<List<Integer>> list = new ArrayList<>();
if (root == null) {
return list;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
List<Integer> subList = new ArrayList<>();//注意:新定义的subList一定要放到while里面
int size = queue.size();//size是queue的size
for (int i = 0; i < size; i++) {
TreeNode temp = queue.poll();
subList.add(temp.val);
if (temp.left != null) {
queue.add(temp.left);
}
if (temp.right != null) {
queue.add(temp.right);
}
}
list.add(subList);
}
return list;
}
}
public class Main {
public static void main(String[] args) {
TreeNode head = new TreeNode(1);//849
TreeNode second = new TreeNode(2);//850
TreeNode three = new TreeNode(3);//851
TreeNode four = new TreeNode(4);//852
TreeNode five = new TreeNode(5);//853
TreeNode six = new TreeNode(6);//854
TreeNode seven = new TreeNode(7);//855
head.right = three;
head.left = second;
second.right = five;
second.left = four;
three.right = seven;
three.left = six;
Solution s = new Solution();
List<List<Integer>> list = s.levelOrder(head);
System.out.println(list);
}
}