一次过,超简单
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int dfs(TreeNode *root, int dep) { 13 if (!root) return dep; 14 return max(dfs(root->left, dep+1), dfs(root->right, dep+1)); 15 } 16 int maxDepth(TreeNode *root) { 17 // Start typing your C/C++ solution below 18 // DO NOT write int main() function 19 return dfs(root, 0); 20 } 21 };
C#
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int dfs(TreeNode root, int dep) { 12 if (root == null) return dep; 13 return Math.Max(dfs(root.left, dep+1), dfs(root.right, dep+1)); 14 } 15 public int MaxDepth(TreeNode root) { 16 return dfs(root, 0); 17 } 18 }