LeetCode-102-二叉树的层序遍历
102. 二叉树的层序遍历
难度中等889收藏分享切换为英文接收动态反馈
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回其层序遍历结果:
[
[3],
[9,20],
[15,7]
]
思路
二叉树的基本算法
image-20210526163617201 image-20210526163837652 image-20210526163940564 image-20210526164054104 image-20210526164139989class Solution {
public static List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if (root == null) {
return ans;
}
LinkedList<TreeNode> deque = new LinkedList<>();
deque.add(root);
int size = 0;
while(!deque.isEmpty()) {
size = deque.size();
List<Integer> curLevel = new ArrayList<>();
for(int i = 0 ; i< size;i++) {
TreeNode cur = deque.pollLast();
curLevel.add(cur.val);
if(cur.left != null) {
deque.addFirst(cur.left);
}
if(cur.right != null) {
deque.addFirst(cur.right);
}
}
ans.add(curLevel);
}
return ans;
}
}
image-20210605152331200
递归解法
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null) return res;
return helper(root, 0);
}
private List<List<Integer>> helper (TreeNode root, int level) {
if(root != null){
if(res.size() <= level){
List<Integer> cur = new ArrayList<>();
res.add(cur);
}
res.get(level).add(root.val);
helper(root.left, level+1);
helper(root.right, level+1);
}
return res;
}
}
image-20210605152519194
网友评论