代码随想录算法训练营Day14
翻转二叉树
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null){
return null;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
对称二叉树
class Solution {
public boolean isSymmetric(TreeNode root) {
return compare(root.left,root.right);
}
public boolean compare(TreeNode left,TreeNode right){
if(left==null&&right!=null){
return false;
}else if(left!=null&&right==null){
return false;
}else if(left==null&&right==null){
return true;
}else if(left.val!=right.val){
return false;
}
boolean outside = compare(left.left,right.right);
boolean inside = compare(left.right,right.left);
return outside&&inside;
}
}
二叉树最大深度
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int ld = maxDepth(root.left);
int rd = maxDepth(root.right);
int depth = Math.max(ld,rd)+1;
return depth;
}
}
二叉树最小深度
这里有坑,注意排除根节点的左/右子节点为空的情况
最小深度是从根节点到叶子结点的距离的最小值.类似上面最大深度的判断方法
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
int ld = minDepth(root.left);
int rd = minDepth(root.right);
if(root.left == null&&root.right != null){
return rd + 1;
}else if(root.left != null&&root.right == null){
return ld+1;
}else{
return Math.min(ld,rd)+1;
}
}
}

浙公网安备 33010602011771号