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.
分析:求二叉树的最大深度
解法一:很容易想到的便是递归(深度优先搜索)
(1)如果根节点是空,则返回0;否则转到(2)
(2) l = 左子树的最大深度; r = 右子树的最大深度; 返回 max(l, r) + 1;
/**
* 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 {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return ;
int l = maxDepth(root->left);
int r = maxDepth(root->right);
return max(l, r) + ;
}
};
解法二:我觉得还可以用广度优先搜索:第i层如果存在节点不为空,则深度加1...最大深度就是这棵树的层数。
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return ;
int depth = ;
queue<TreeNode*> node_que;
TreeNode* temp;
node_que.push(root);
while(!node_que.empty()){
int size = node_que.size();
while(size--){
temp = node_que.front();
node_que.pop();
if(temp->left != NULL)
node_que.push(temp->left);
if(temp->right != NULL)
node_que.push(temp->right);
}
depth++;
}
return depth; }
};