题目描述
求给定二叉树的最大深度,
最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量。
代码一:
通过递归
public int maxDepth (TreeNode root) {// write code hereif(root==null)return 0;return Math.max(maxDepth(root.left)+1, maxDepth(root.right)+1);}
代码二:
通过层次遍历
//二叉树的深度public static int maxDepth (TreeNode root) {if(root==null)return 0;// return Math.max(maxDepth(root.left)+1, maxDepth(root.right)+1);Queue<TreeNode> q = new LinkedList<TreeNode>();q.add(root);int res = 0;while(!q.isEmpty()) {int size = q.size();for(int i=0;i<size;i++) {TreeNode node = q.poll();if(node.left!=null)q.add(node.left);if(node.right!=null)q.add(node.right);}res++;}return res;}
