226.翻转二叉树
题目链接/文章讲解/视频讲解: 代码随想录
可以前后遍历,不能中序遍历(交换后重复
//DFS递归
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
invertTree(root.left);
invertTree(root.right);
swapChildren(root);
return root;
}
private void swapChildren(TreeNode root) {
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}
}
101. 对称二叉树
题目链接/文章讲解/视频讲解: 代码随想录
比较根节点的左子树与右子树是不是相互翻转
递归法,比较左右节点,左节点的左孩子右节点的右孩子,左节点的右孩子右节点的左孩子
public boolean isSymmetric1(TreeNode root) {
return compare(root.left, root.right);
}
private boolean compare(TreeNode left, TreeNode right) {
if (left == null && right != null) {
return false;
}
if (left != null && right == null) {
return false;
}
if (left == null && right == null) {
return true;
}
if (left.val != right.val) {
return false;
}
// 比较外侧
boolean compareOutside = compare(left.left, right.right);
// 比较内侧
boolean compareInside = compare(left.right, right.left);
return compareOutside && compareInside;
}
104.二叉树的最大深度
题目链接/文章讲解/视频讲解: 代码随想录
class Solution {
/**
* 递归法
*/
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
111.二叉树的最小深度
题目链接/文章讲解/视频讲解:代码随想录
最小深度是从根节点到最近叶子节点的最短路径上的节点数量,左右孩子都为空的才是叶子节点
递归法
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
if (root.left == null) {
return rightDepth + 1;
}
if (root.right == null) {
return leftDepth + 1;
}
// 左右结点都不为null
return Math.min(leftDepth, rightDepth) + 1;
}
}