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.
Subscribe to see which companies asked this question.
dfs,一下子忘了。。。
基本就是迭代。
顺便复习一下树结构:
struct tree()
{
int num;
tree* left;
tree* right;
tree(int x):num(x), left(NULL),right(NULL){}
}
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int max(int a, int b){
return (a>b)?a:b;
}
public:
int maxDepth(TreeNode* root) {
if (root == NULL)
return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};