问题描述:
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.
方法一:深度优先搜索!
/**
* 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 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return max(left, right)+1;
}
};
方法二:广度优先搜索!
class Solution {
public:
int maxDepth(TreeNode* root) {
return BFSsolution(root);
}
int BFSsolution(TreeNode *root){
if(root == NULL) return 0;
queue<TreeNode *> que;
que.push(root);
int depth = 0, count;
TreeNode *left, *right;
while(que.empty() == false){
depth++;
count = que.size();
for(int i = 0; i < count; i++){
left = que.front()->left;
if(left) que.push(left);
right = que.front()->right;
if(right) que.push(right);
que.pop();
}
}
return depth;
}
};
227




被折叠的 条评论
为什么被折叠?



