对称二叉树
递归法
- 1.确定递归函数的参数和返回值
boolean compare(TreeNode left, TreeNode right)
判断左右子树是否相同,返回布尔值- 2.确定终止条件
– 左节点空,右节点不空 ,return false
– 左节点不空,右节点空,return false
– 左右都空,return true
– 左右节点都不空,比较节点值,不同则return false
最后只剩下,左右节点都不空,且节点值相同- 3.单层递归逻辑
只用处理,左右节点不空且数值相同
– 比较二叉树外侧是否对称:传入的是左节点的左孩子和右节点的右孩子
– 比较二叉树内侧是否对称:传入左节点右孩子和右节点左孩子
– 左右都对成则return true,有一侧不对称就return false
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
return compare(root.left, root.right);
}
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);
boolean isSame = outside && inside;
return isSame;
}
}
迭代法
使用双端队列
class Solution {
public boolean isSymmetric(TreeNode root){
if (root == null) return true;
Deque<TreeNode> que = new LinkedList<>();
que.push(root.left);
que.push(root.right);
while(!que.isEmpty()){
TreeNode leftNode = que.pollFirst();
TreeNode rightNode = que.pollLast();
if (leftNode == null && rightNode == null) { //左右都空
continue;
}
if(leftNode == null || rightNode == null || leftNode.val != rightNode.val)
return false;
que.offerFirst(leftNode.left);
que.offerFirst(leftNode.right);
que.offerLast(rightNode.right);
que.offerLast(rightNode.left);
}
return true;
}
}
二叉树最大深度
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;
}
}
二叉树最小深度
class Solution {
/**
* 递归法,相比求MaxDepth要复杂点
* 因为最小深度是从根节点到最近**叶子节点**的最短路径上的节点数量
*/
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;
}
}