题目:
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
解题思路:
递归求得左子树的深度left_depth,右子树的深度right_depth,则 ans = max(left_depth, right_depth) + 1;
代码:
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 maxDepth(TreeNode *root) { 13 if (root == NULL){ 14 return 0; 15 } 16 int left_depth = maxDepth(root->left); 17 int right_depth = maxDepth(root->right); 18 return max(left_depth, right_depth) + 1; 19 20 } 21 inline int max(int a, int b) { 22 return a > b ? a : b; 23 } 24 };