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代码:

  1. public int maxDepth(TreeNode root) {
  2. if(root==null) return 0;
  3. ArrayList<TreeNode> al = new ArrayList<TreeNode>();
  4. TreeNode tmp;
  5. int index=0;
  6. int level=1;
  7. int i=0; // the start
  8. al.add(root);
  9. index++; // the end
  10. int cnt=1; // the number
  11. while(cnt>0) {
  12. cnt=0;
  13. while(i<index) {
  14. tmp=al.get(i);
  15. if(tmp.left!=null) {
  16. al.add(tmp.left);
  17. cnt++;
  18. }
  19. if(tmp.right!=null) {
  20. al.add(tmp.right);
  21. cnt++;
  22. }
  23. i++;
  24. }
  25. index=index+cnt;
  26. if(cnt!=0) level++;
  27. }
  28. return level;
  29. }

递归:

  1. public int maxDepth(TreeNode root) {
  2. if(root==null) return 0;
  3. return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
  4. }
posted @ 2014-07-29 22:25  purejade  阅读(70)  评论(0编辑  收藏  举报