Day15好多题目
LeetCode十道层序遍历题目
- 二叉树的层序遍历
- 经典队列
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new ArrayDeque<>();
List<List<Integer>> res = new ArrayList<>();
if(root == null){
return res;
}
queue.add(root);
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> temp = new ArrayList<>();
for(int i = 0; i < size; i++ ){
TreeNode node = queue.poll();
temp.add(node.val);
if(node.left != null){
queue.add(node.left);
}
if(node.right != null){
queue.add(node.right);
}
}
// 这里就是每一层的结束
res.add(temp);
}
return res;
}
}
- 递归法
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
// 递归法
List<List<Integer>> res = new ArrayList<>();
help(root,res,0);
return res;
}
public void help(TreeNode root,List<List<Integer>> res , int depth){
// 很巧妙,以depth作为返回列表的index
if(root == null) return ;
if(res.isEmpty() || res.size()-1 < depth){
List<Integer> temp = new ArrayList<>();
res.add(temp);
}
// depth作为index
res.get(depth).add(root.val);
help(root.left,res,depth+1);
help(root.right,res,depth+1);
}
}
- 二叉树的层次遍历II
核心思想:自底向上遍历,直接把遍历的结果reverse - 二叉树的右视图
核心思想:层序遍历的时候,如果是第size-1个,那么就是最右边的,加入到结果集
class Solution {
public List<Integer> rightSideView(TreeNode root) {
// 层级遍历的最后一个加进去就行
List<Integer> res = new ArrayList<>();
Queue<TreeNode> queue = new ArrayDeque<>();
if(root == null){
return res;
}
queue.add(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.add(node.left);
}
if(node.right != null){
queue.add(node.right);
}
}
}
return res;
}
}
- 二叉树的层平均值
核心思想:只要在每一层遍历结束的时候计算平均值 - N叉树的层序遍历
核心思想:和二叉树没什么两样,遍历把所有children都加入队列中 - 在每个树行中找最大值
核心思想:在每层的过程中保存最大值 - 填充每个节点的下一个右侧节点指针
核心思想:在每层的遍历中,每个元素都指向队列中下一个元素,使用peek即可 - 填充每个节点的下一个右侧节点指针II
核心思想:和上一个题目好像没什么不同,直接提交代码就ac了 - 二叉树的最大深度
核心思想:层序遍历记录层数即可 - 二叉树的最小深度
核心思想:遇到没有左右子节点的直接返回高度。
LeetCode226 翻转二叉树:交换左右子树
核心思想:使用先序或者后序遍历即可,在过程中进行左右子树的交换,层序也可。中序遍历注意:当你先交换左,然后交换中的时候,左子树和右子树交换了位置,接下来应该继续遍历左,否则相当于右子树没遍历。
class Solution {
public TreeNode invertTree(TreeNode root) {
help(root);
return root;
}
public void help(TreeNode root){
if(root == null) return;
help(root.left);
help(root.right);
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
}
LeetCode 对称二叉树:判断是不是对称的
核心思想:也是怎么遍历都行,要注意的就是判断当前节点的 left.left 和 right.right值相同,left.right和right.left值相同。使用层级遍历也是一样,下面提供层级遍历的代码
class Solution {
public boolean isSymmetric(TreeNode root) {
// 使用栈
Stack<TreeNode> stack = new Stack<>();
if(root == null) return true;
stack.push(root.left);
stack.push(root.right);
while(!stack.isEmpty()){
TreeNode left = stack.pop();
TreeNode right = stack.pop();
if(left == null && right == null){
continue;
}
if(left == null || right == null || left.val != right.val){
return false;
}
// 顺序一定要对,左节点的左和右节点的右相同才是对称
stack.push(left.left);
stack.push(right.right);
// 注意顺序
stack.push(left.right);
stack.push(right.left);
}
return true;
}
}



被折叠的 条评论
为什么被折叠?



