递归实现
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public int maxDepth(TreeNode root) {if(root==null){return 0;}else{return Math.max(maxDepth(root.left),maxDepth(root.right))+1;}}
}
队列实现,遍历每一行元素后dept++
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public int maxDepth(TreeNode root) {if(root==null){return 0;}Queue<TreeNode> queue = new LinkedList<TreeNode>();queue.offer(root);int dept=0;while(!queue.isEmpty()){int size=queue.size();while(size>0){TreeNode node=queue.poll();if(node.left!=null){queue.offer(node.left);}if(node.right!=null){queue.offer(node.right);}size--;}dept++;}return dept;}
}