给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
返回它的最大深度 3 。
上期的问题是:128,对称二叉树
1public boolean isSymmetric(TreeNode root) {
2 if (root == null) return true;
3 return isMirror(root.left, root.right);
4}
5
6public boolean isMirror(TreeNode p, TreeNode q) {
7 if (p == null && q == null) return true;
8 if (p == null || q == null) return false;
9 return (p.val == q.val) && isMirror(p.left, q.right) && isMirror(p.right, q.left);
10}
解析:
和上一题相同的树基本上一样。我们再来看一下非递归的写法
1public boolean isSymmetric(TreeNode root) {
2 Queue<TreeNode> q = new LinkedList<>();
3 if (root == null) return true;
4 q.add(root.left);
5 q.add(root.right);
6 while (q.size() > 1) {
7 TreeNode left = q.poll(), right = q.poll();
8 if (left == null && right == null) continue;
9 if (left == null ^ right == null) return false;
10 if (left.val != right.val) return false;
11 q.add(left.left);
12 q.add(right.right);
13 q.add(left.right);
14 q.add(right.left);
15 }
16 return true;
17}