Maximum Depth of Binary Tree
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.
非递归实现: 用ArrayList来实现层次遍历,用cnt和index来记录每层节点数目
java代码:
- public int maxDepth(TreeNode root) {
- if(root==null) return 0;
- ArrayList<TreeNode> al = new ArrayList<TreeNode>();
- TreeNode tmp;
- int index=0;
- int level=1;
- int i=0; // the start
- al.add(root);
- index++; // the end
- int cnt=1; // the number
- while(cnt>0) {
- cnt=0;
- while(i<index) {
- tmp=al.get(i);
- if(tmp.left!=null) {
- al.add(tmp.left);
- cnt++;
- }
- if(tmp.right!=null) {
- al.add(tmp.right);
- cnt++;
- }
- i++;
- }
- index=index+cnt;
- if(cnt!=0) level++;
- }
- return level;
- }
递归:
- public int maxDepth(TreeNode root) {
- if(root==null) return 0;
- return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
- }