递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
int lchildh,rchildh;
if(root == null)
return 0;
else{
lchildh = maxDepth(root.left);
rchildh = maxDepth(root.right);
return (lchildh > rchildh ? (lchildh + 1) : (rchildh +1) );
}
}
//return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
非递归(队列实现)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
/**
*pCount当前层的节点数
*preCount前一层的节点数
*/
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
int preCount = 1;
int pCount = 0;
int level = 0;
while(!q.isEmpty()){
TreeNode temp = q.poll();
preCount--;
if(temp.left != null){
q.offer(temp.left);
pCount++;
}
if(temp.right != null){
q.offer(temp.right);
pCount++;
}
if(preCount == 0){
preCount = pCount;
pCount = 0;
level++;
}
}
return level;
}
}