Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
return its depth = 3.
解法
我是按照按层遍历的方法解的这道题,就是利用队列size确定每层的个数,然后确定总的层数
具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
class { public int maxDepth(TreeNode root) { int level = 0; if (root == null) return level; Queue<TreeNode> q = new LinkedList<TreeNode>(); q.offer(root); while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i < size; i++) { TreeNode tmp = q.poll(); if (tmp.left != null) { q.offer(tmp.left); } if (tmp.right != null) { q.offer(tmp.right); } } level++; } return level; } }
|
网上看到可以用递归解这题,确实,代码相当简洁
1 2 3 4 5
|
public class { public int maxDepth(TreeNode root) { return root == null ? 0 : (1 + Math.max(maxDepth(root.left), maxDepth(root.right))); } }
|
近期评论