LeetCode 102. 二叉树的层序遍历
102. 二叉树的层序遍历
Solution
思路:搞一个深度,然后放到对应的层次里。这里开List
嵌套的时候有点坑,不过根据list
的容量大小和层次的高度关系,来进行创建。这里的NewNode
不能共用。题解代码是 用for循环搞出来那一层的。普通的BFS
是弹出一个。见下面代码二。
更新:LeetCode 429 N叉树的层序遍历。代码三
///代码一
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) return new ArrayList<>();
List<List<Integer>> lists = new ArrayList<>();
Queue<NewNode> queue = new ArrayDeque<>();
NewNode newNode = new NewNode();
newNode.node = root;
newNode.deep = 0;
queue.add(newNode);
while (!queue.isEmpty()) {
NewNode t = queue.remove();
if (lists.size() <= t.deep) {
lists.add(new ArrayList<>());
}
lists.get(t.deep).add(t.node.val);
if (t.node.left != null) {
NewNode l = new NewNode();
l.node = t.node.left;
l.deep = t.deep + 1;
queue.add(l);
}
if (t.node.right != null) {
NewNode r = new NewNode();
r.node = t.node.right;
r.deep = t.deep + 1;
queue.add(r);
}
}
return lists;
}
}
class NewNode {
TreeNode node;
int deep;
}
//代码二
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> lists = new ArrayList<>();
if (root == null) return lists;
Queue<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
while (!queue.isEmpty()) {
List<Integer> level = new ArrayList<>();
int sz = queue.size();
for (int i = 0; i < sz; i++) {
TreeNode node = queue.remove();
level.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
lists.add(level);
}
return lists;
}
}
//代码三
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> ans = new ArrayList<>();
if (root == null) return ans;
Deque<Node> queue = new ArrayDeque<>();
queue.add(root);
while (!queue.isEmpty()) {
int sz = queue.size();
List<Integer> level = new ArrayList<>();
for (int i = 0; i < sz; i++) {
Node child = queue.remove();
level.add(child.val);
for (Node node : child.children) {
queue.add(node);
}
}
ans.add(level);
}
return ans;
}
}
埋骨何须桑梓地,人生无处不青山