226. 翻转二叉树
关键点:递归法
class Solution {
public TreeNode invertTree(TreeNode root) {
//使用前序或者后序
if(root == null) return root;
swapTreeNode(root);
invertTree(root.left);
invertTree(root.right);
return root;
}
private void swapTreeNode(TreeNode node) {
TreeNode treeNode = node.left;
node.left = node.right;
node.right = treeNode;
}
}
101. 对称二叉树
关键点:递归法
后序遍历:需要将孩子节点信息返回就要使用后序遍历
class Solution {
public boolean isSymmetric(TreeNode root) {
return compare(root.left, root.right);
}
//将左边的左节点和右边的右节点分别做比较
private boolean compare(TreeNode left, TreeNode right){
//剪枝操作:
//1. 左空 右空:true
if(left==null && right==null) return true;
//2. 左空 右不空:false
else if(left==null && right!=null) return false;
//3. 左不空 右空:false
else if(left!=null && right==null) return false;
//4. 左右值不相等:false
//⏰ 此处是比较值 而不是left和right,因为他们的左右指针都是不相等的
else if(left.val!=right.val) return false;
//5. 左右相等 向下比较
else{
boolean outside = compare(left.left, right.right);
boolean inside = compare(left.right, right.left);
return outside && inside;
}
}
}
104. 二叉树的最大深度
关键点:
求高度:后序遍历
求深度:前序遍历
当前使用后序遍历,高度=深度
class Solution {
public int maxDepth(TreeNode root) {
return count(root);
}
private int count(TreeNode root){
if(root==null) return 0;
//后序遍历 左右中
int leftDepth = count(root.left);
int rightDepth = count(root.right);
//⏰ 中(处理逻辑),对当前节点++,且+当前节点下的子节点的最大高度
return 1+Math.max(leftDepth, rightDepth);
}
}
111. 二叉树的最小深度
关键点:叶子节点是指没有子节点的节点(额外考虑度为1的节点)
class Solution {
//求深度:用后序求高度的方式
//处理逻辑中需要额外处理度为1的节点,其某一端为null,但其不是叶子节点
public int minDepth(TreeNode root) {
if(root==null) return 0;
int left = minDepth(root.left);
int right = minDepth(root.right);
//额外考虑非叶子节点的情况
//求最小深度和求最大深度遍历的逻辑相同 但中间的处理逻辑不同
if(root.left!=null && root.right==null){
return 1+left;
}else if(root.left==null && root.right!=null){
return 1+right;
}else{
return 1+Math.min(left,right);
}
}
}