题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
代码一
思想:
层次遍历,通过对每一层的遍历,每遍历完一层就加1 也就能求得二叉树的深度
public static int TreeDepth(TreeNode root) {//通过队列来实现层次遍历Queue<TreeNode> q = new LinkedList<TreeNode>();q.add(root);int count = 0;int nextcount = q.size();//用来保存每一层的节点个数int temp=0;//记录深度值while(q.size()!=0){TreeNode t = q.poll();count++;//记录当前层节点的个数if(t.left!=null)q.add(t.left);if(t.right!=null)q.add(t.right);if(count==nextcount)//当循环次数为当前层的节点次数时说明已经遍历了一层所以深度加1{count = 0;temp++;nextcount=q.size();}}return temp;}
代码一
思想:
递归
public int TreeDepth(TreeNode root) {if(root==null){return 0;}int left=TreeDepth(root.left);int right=TreeDepth(root.right);return Math.max(left,right)+1;}
