LeetCode: Maximum Depth of Binary Tree

一次过,超简单

 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#

 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 }
View Code
原文地址:https://www.cnblogs.com/yingzhongwen/p/3006537.html