/**
* 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;
}
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
//前序遍历,这才是求深度的逻辑
class Solution {
//要定义在maxDepth外面,只是更改覆盖maxnum并没有,对它+1什么的
int maxnum = 0;
public int maxDepth(TreeNode root) {
ans(root,maxnum);
return maxnum;
}
public void ans(TreeNode node,int tmp){
if(node==null){
return;
}
tmp++;//tmp表示当前节点,node的深度,加完1之后才是。
maxnum = maxnum<tmp?tmp:maxnum;
ans(node.left,tmp);
ans(node.right,tmp);
tmp--;
}
}
//迭代法,层序遍历
class Solution {
public int maxDepth(TreeNode root) {
if(root==null){
return 0;
}
Deque<TreeNode> que = new LinkedList<>();
int depth = 0;
que.offer(root);
while(!que.isEmpty()){
int size = que.size();
//只加了一句这个
depth++;
for(int i=0;i<size;i++){
TreeNode tmp = que.poll();
if(tmp.left!=null){
que.offer(tmp.left);
}
if(tmp.right!=null){
que.offer(tmp.right);
}
}
}
return depth;
}
}