文章目录
- 题目描述
- 代码 & 思路
题目描述
- 全局变量ans,遍历一遍树更新ans即可
- 带着 depth 跑 DFS
代码 & 思路
写成dfs了,确实是bfs
/*** 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 {// 全局变量maxint max = 0;public int maxDepth(TreeNode root) {dfs(root,0);return max;}// dfs遍历结点void dfs(TreeNode now, int depth){// 递归结束,进行max更新if(now == null){max = Math.max(depth, max);return;}dfs(now.left,depth+1);dfs(now.right,depth+1);}
}