226. 翻转二叉树
递归,用先序或者后序翻转。用中序会比较绕,因为左根右,左子树反转完之后,根,把左子树反转到了右边,应该是左根左递归。
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;
}
}
101. 对称二叉树
比较两个树内侧和外侧是否相等,所以需要后序遍历,左右子树都比较完了,看一下结果怎么样。
1.确定参数和返回值,比较是否对称,所以传入左右两个数的头节点,返回Boolean。
2.确定跳出条件,左右有一个为空,false;都空true;都不空但是值不相等false,否则(值相等)进入递归。
3.单层递归
- 比较二叉树外侧是否对称:传入的是左节点的左孩子,右节点的右孩子。
- 比较内侧是否对称,传入左节点的右孩子,右节点的左孩子。
- 如果左右都对称就返回true ,有一侧不对称就返回false 。
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;
}else{
boolean outside = compare(left.left,right.right);
boolean inside = compare(left.right,right.left);
return outside&&inside;
}
}
}
104. 二叉树的最大深度
后序遍历,找到左右子树的高度,然后返回他们的最大值+1
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left,right)+1;
}
}
111. 二叉树的最小深度
与最大深度的区别,最小深度是从根节点到最近叶子节点的最短路径上的节点数量。所以如果子树左或者右是空的话不算。
class Solution {
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 right+1;
}
if(root.left!=null&&root.right==null){
return left+1;
}
return Math.min(left,right)+1;
}
}