LeetCode——Maxium Depth of Binary Tree
# 104
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.
这一题的目的是求出二叉树中的最大深度。显然用递归的方式是可以实现这一题的。无论是DFS还是BFS都是可以的。
- C++
/**
* 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_depth = 0;
public:
int maxDepth(TreeNode* root) {
if(!root)
return 0;
return max_Depth(root,1);
}
int max_Depth(TreeNode* root,int now_depth) {
if(!root)
return 0;
if(now_depth > max_depth) {
max_depth = now_depth;
}
max_Depth(root -> left,now_depth + 1);
max_Depth(root -> right,now_depth + 1);
return max_depth;
}
};
还有一种方法,也是DFS,更加简洁。
- C++
/**
* 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;
return 1 + max( maxDepth(root->left), maxDepth(root->right) );
}
};
除了DFS,BFS也能实现这个题目,但相对而言,BFS稍微复杂一点,需要借助到其他的结构,队列或者栈。
- C++/queue
/**
* 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;
queue<TreeNode *> Q;
Q.push(root);
int count = 1;
int depth = 0;
while(!Q.empty()){
TreeNode *tmp = Q.front();
Q.pop();
count--;
if(tmp->left){
Q.push(tmp->left);
}
if(tmp->right){
Q.push(tmp->right);
}
if(count == 0){
depth++;
count = Q.size();
}
}
return depth;
}
};
- C++/stack
class Solution {
public:
int maxDepth(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL) return 0;
stack<TreeNode*> S;
int maxDepth = 0;
TreeNode *prev = NULL;
S.push(root);
while (!S.empty()) {
TreeNode *curr = S.top();
if (prev == NULL || prev->left == curr || prev->right == curr) {
if (curr->left)
S.push(curr->left);
else if (curr->right)
S.push(curr->right);
} else if (curr->left == prev) {
if (curr->right)
S.push(curr->right);
} else {
S.pop();
}
prev = curr;
if (S.size() > maxDepth)
maxDepth = S.size();
}
return maxDepth;
}
};