// 层序遍历 递归
class Solution {
List<List<Integer>> res;
public List<List<Integer>> levelOrder(TreeNode root) {
res = new ArrayList<>();
if(root == null) return res;
dfs(root, 1);
return res;
}
private void dfs(TreeNode root, int depth){
if(root == null) return;
if(depth > res.size()){
res.add(new ArrayList<Integer>());
}
res.get(depth-1).add(root.val);
dfs(root.left, depth + 1);
dfs(root.right, depth + 1);
}
}
//迭代
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Deque<TreeNode> queue = new LinkedList<>();
List<List<Integer>> res = new LinkedList<>();
if(root == null) return res;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
ArrayList<Integer> p = new ArrayList<>();
for(int i=0;i<size;i++){
TreeNode node = queue.poll();
p.add(node.val);
if(node.left!=null) queue.offer(node.left);
if(node.right!=null) queue.offer(node.right);
}
res.add(p);
}
return res;
}
}
进阶:之字形遍历
103.二叉树的锯齿形层序便利
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
Deque<TreeNode> queue = new LinkedList<>();
List<List<Integer>> res = new LinkedList<>();
if(root == null) return res;
int flag = 0;
queue.offer(root);
while(!queue.isEmpty()){
flag++;
int size = queue.size();
LinkedList<Integer> p = new LinkedList<>();
for(int i=0;i<size;i++){
TreeNode node = queue.poll();
p.add(node.val);
if(node.left!=null) queue.offer(node.left);
if(node.right!=null) queue.offer(node.right);
}
if(flag%2==0) Collections.reverse(p);
res.add(p);
}
return res;
}
}
// 迭代
class Solution {
public List<Integer> rightSideView(TreeNode root) {
Deque<TreeNode> queue = new LinkedList<>();
List<Integer> res = new LinkedList<>();
if(root == null) return res;
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0;i<size;i++){
TreeNode node = queue.poll();
if(i==size-1) res.add(node.val);
if(node.left!=null) queue.offer(node.left);
if(node.right!=null) queue.offer(node.right);
}
}
return res;
}
}
// 递归
class Solution {
List<Integer> res = new LinkedList<>();
public List<Integer> rightSideView(TreeNode root) {
if(root == null) return res;
dfs(root, 1);
return res;
}
private void dfs(TreeNode root, int depth){
if(root == null) return;
if(depth > res.size()){
res.add(root.val);
}
dfs(root.right, depth+1);
dfs(root.left, depth+1);
return;
}
}