226.翻转二叉树
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) return null;
swapChildren(root);
invertTree(root.left);
invertTree(root.right);
return root;
}
private void swapChildren(TreeNode root) {
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
}
}
101. 对称二叉树
class Solution {
public boolean isSymmetric(TreeNode root) {
boolean result = compare(root.left,root.right);
return result;
}
boolean compare(TreeNode a, TreeNode b){
if(a!=null &&b == null ) return false;
if(a==null &&b !=null ) return false;
if(a== null && b== null) return true;
if(a.val != b.val ) return false;
boolean compareleft = compare(a.left,b.right);
boolean compareright = compare(a.right,b.left);
return compareleft && compareright;
}
}
如果是相等的则不需要处理,继续向下递归即可
104.二叉树的最大深度
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) return 0;
int i = maxDepth(root.left);
int j = maxDepth(root.right);
return 1+Math.max(i,j);
}
}
111.二叉树的最小深度
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
int m1 = minDepth(root.left);
int m2 = minDepth(root.right);
//1.如果左孩子和右孩子有为空的情况,直接返回m1+m2+1
//2.如果都不为空,返回较小深度+1
return root.left == null || root.right == null ? m1 + m2 + 1 : Math.min(m1,m2) + 1;
}
}