一、层次遍历
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例: 二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层序遍历结果:
[
[3],
[9,20],
[15,7]
]
来源:力扣(LeetCode)
Ans:
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if(root==null){
return ans;
}
List<TreeNode> tmp = new ArrayList<>();
tmp.add(root);
while (tmp.size()!=0){
List<Integer> ele = new ArrayList<>();
int size = tmp.size();
for(int i=0; i<size; i++){
TreeNode cur = tmp.get(0);
ele.add(cur.val);
if(cur.left!=null){
tmp.add(cur.left);
}
if(cur.right!=null){
tmp.add(cur.right);
}
tmp.remove(0);
}
ans.add(ele);
}
return ans;
}
}
二、锯齿形遍历
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。 例如: 给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层序遍历如下:
[
[3],
[20,9],
[15,7]
]
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if(root==null){
return ans;
}
List<TreeNode> tmp = new ArrayList<>();
tmp.add(root);
boolean toRight = false;
while (tmp.size()!=0){
List<Integer> ele = new ArrayList<>();
int size = tmp.size();
for(int i=0; i<size; i++){
TreeNode cur = tmp.get(0);
if(toRight){
ele.add(0, cur.val);
}else{
ele.add(cur.val);
}
if(cur.left!=null){
tmp.add(cur.left);
}
if(cur.right!=null){
tmp.add(cur.right);
}
tmp.remove(0);
}
toRight = !toRight;
ans.add(ele);
}
return ans;
}
}