Java解决:递归和常规解法
二叉树的最大深度
http://www.nowcoder.com/questionTerminal/8a2b2bf6c19b4f23a9bdb9b233eefa73
方法1:简单递归方式
public class TreeNode{ public int maxDepth(TreeNode root){ if(root==null)return 0; int leftDepth = maxDepth(root.left); int rightDepth = maxDepth(root.right); int res = Math.max(leftDepth,rightDepth); return res+1; } }
方法2:通过链表
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 * @return int整型 */ //递归 /* public int maxDepth (TreeNode root) { if(root == null)return 0; int leftDepth = maxDepth(root.left); int rightDepth = maxDepth(root.right); return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1; // write code here } */ public int maxDepth(TreeNode root){ if(root == null)return 0; LinkedList<TreeNode> list = new LinkedList<>(); list.offer(root); int max = 0; int level = 0; int size = 0; int cur = 0; while(!list.isEmpty()){ size = list.size(); max = Math.max(max,size); cur = 0; while(cur < size){ TreeNode node = list.poll(); cur++; if(node.left != null){ list.offer(node.left); } if(node.right != null){ list.offer(node.right); } } level++; } //System.out.println("二叉树最大宽度为:"+max); return level; } }