题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

代码一

思想:
层次遍历,通过对每一层的遍历,每遍历完一层就加1 也就能求得二叉树的深度

  1. public static int TreeDepth(TreeNode root) {
  2. //通过队列来实现层次遍历
  3. Queue<TreeNode> q = new LinkedList<TreeNode>();
  4. q.add(root);
  5. int count = 0;
  6. int nextcount = q.size();//用来保存每一层的节点个数
  7. int temp=0;//记录深度值
  8. while(q.size()!=0)
  9. {
  10. TreeNode t = q.poll();
  11. count++;//记录当前层节点的个数
  12. if(t.left!=null)q.add(t.left);
  13. if(t.right!=null)q.add(t.right);
  14. if(count==nextcount)//当循环次数为当前层的节点次数时说明已经遍历了一层所以深度加1
  15. {
  16. count = 0;
  17. temp++;
  18. nextcount=q.size();
  19. }
  20. }
  21. return temp;
  22. }

代码一

思想:
递归

  1. public int TreeDepth(TreeNode root) {
  2. if(root==null){
  3. return 0;
  4. }
  5. int left=TreeDepth(root.left);
  6. int right=TreeDepth(root.right);
  7. return Math.max(left,right)+1;
  8. }