100. 对称二叉树
给定一个二叉树,检查它是否是镜像对称的
例如,二叉树 [1,2,2,3,4,4,3] 是对称的
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的
说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分
public boolean isSymmetric(TreeNode root) {
if (null == root) {
return true;
}
return isMirror(root.left, root.right);
}
public boolean isMirror(TreeNode left, TreeNode right) {
// 节点都为空(此节点相等)
if (null == left && null == right) {
return true;
} else if (null == left || null == right) { // 其中一个为空(不相等)
return false;
} else if (left.val == right.val) { // 节点不为空,值相等,继续向下判断
return isMirror(left.left, right.right) && isMirror(left.right, right.left);
}
return false;
}
104. 二叉树的最大深度
给定一个二叉树,找出其最大深度
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数
说明: 叶子节点是指没有子节点的节点
示例:
给定二叉树 [3,9,20,null,null,15,7]
返回它的最大深度 3
public int maxDepth(TreeNode root) {
return null == root ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
107. 二叉树的层序遍历 Ⅱ
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
例如:
给定二叉树 [3,9,20,null,null,15,7]
返回其自底向上的层次遍历为:
private static List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
if (root == null) {
return lists;
}
List<TreeNode> list1 = new ArrayList<TreeNode>();
List<TreeNode> list2 = new ArrayList<TreeNode>();
list1.add(root);
TreeNode temp = null;
while (list1.size() != 0) {
List<Integer> inner = new ArrayList<Integer>();
for (int i = 0; i < list1.size(); i++) {
temp = list1.get(i);
inner.add(temp.val);
if (temp.left != null) {
list2.add(temp.left);
}
if (temp.right != null) {
list2.add(temp.right);
}
}
lists.add(0, inner);
list1 = list2;
list2 = new ArrayList<TreeNode>();
}
return lists;
}