代码随想录算法训练营第十八天 | 层序遍历、翻转二叉树 、对称二叉树
最近有些松懈,需要努努力了,奥里给!!!加油
今天题目没有完全做完,只做了一分部,以后还要回顾一下,这个部分不是很熟练。
层序遍历 link
思路:使用队列
根据视频,记住模板
推荐视频:代码随想录
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
fun(root);
return res;
}
public void fun(TreeNode root) {
// 使用队列
if (root == null)
return;
Queue<TreeNode> que = new LinkedList<>();
que.offer(root);// 先放入根节点
while (!que.isEmpty()) {
List<Integer> list = new ArrayList<>();// 存放每层元素
int len = que.size();// 注意:len存放的是*当前层*元素的数量
while (len > 0) {
TreeNode temp = que.poll();
list.add(temp.val);
if (temp.left != null)
que.offer(temp.left);
if (temp.right != null)
que.offer(temp.right);
len--;
}
res.add(list);
}
}
}
翻转二叉树link
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点
思路:递归进行求解
class Solution {
public TreeNode invertTree(TreeNode root) {
//结束条件
if (root == null)
return null;
invertTree(root.left);
invertTree(root.right);
swap(root);
return root;
}
void swap(TreeNode root) {
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
}
对称二叉树 link
题目:给你一个二叉树的根节点 root , 检查它是否轴对称。
递归求解
class Solution {
public boolean isSymmetric(TreeNode root) {
// 递归方法
return fun(root.left, root.right);
}
public boolean fun(TreeNode left, TreeNode right) {
// 检查两个节点是否对称时,需要确保:
// 两个节点都是空的(即,都是叶子节点的末端)。
// 两个节点中有一个是空的(这会导致不对称)。
// 两个节点的值相等,并且它们的左子树与右子树是对称的,以及它们的右子树与左子树也是对称的。
if (left == null && right == null)
return true;
if (left == null || right == null || left.val != right.val)
return false;
// 比较外侧
boolean outside = fun(left.left, right.right);
// 比较内侧
boolean inside = fun(left.right, right.left);
return outside && inside;// 同true为true
}
}
希望对您有帮助,谢谢!
本文介绍了在代码随想录算法训练营中的三个问题:层序遍历使用队列实现,翻转二叉树通过递归交换节点,以及判断对称二叉树的递归方法。作者分享了解题思路和关键代码片段,旨在提升读者的编程技能。


404

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



