max tree depth
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
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
if(!root->right && !root->left)
return 1;
else if(root->left&&root->right)
return 1+max( maxDepth(root->left),maxDepth(root->right) );
else if(root->left&&!root->right)
return 1+maxDepth(root->left);
else
return 1+maxDepth(root->right);
}
};
BFS
int solution2(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;
}