試題請參見: https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/
題目概述
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
解題思路
經典數據結構作業題, 當然也是經典的面試題.源代碼
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
if ( root == NULL ) {
return 0;
} else {
int leftDepth = maxDepth(root->left) + 1;
int rightDepth = maxDepth(root->right) + 1;
return ( leftDepth > rightDepth ? leftDepth : rightDepth );
}
}
};