题目描述
在线提交地址:点击跳转
方法一:递归
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
int leftDepth = maxDepth(root->left) + 1;
int rightDepth = maxDepth(root->right) + 1;
return leftDepth > rightDepth ? leftDepth : rightDepth;
}
一行版本:
int maxDepth(TreeNode* root) {
return root == NULL ? 0 : max(maxDepth(root->left) + 1, maxDepth(root->right) + 1);
}
提交结果
方法二:深度优先(栈)
栈实现的是深度优先遍历,先将二叉树的上层结点压入栈底,再取栈顶的下层结点操作,最后操作栈底的上层结点,故利用栈的特性可以实现深度优先遍历
- 根结点压栈,并将当前结点深度 1 压栈
- 取出栈顶结点同时获取出栈结点的深度,并根据此结点将其子结点以及对应的深度压栈。
- 若此时取出结点的深度大于res_depth,则更新res_depth,否则不更新
- 重复2、3,直到栈空
int maxDepth(TreeNode* root) {
stack<TreeNode*> s;
stack<int> depth;
int res_depth = 0;
if(root != NULL){
s.push(root);
depth.push(1);
}
while( !s.empty() ){
TreeNode* node = s.top();
s.pop();
int temp_depth = depth.top();
depth.pop();
res_depth = temp_depth > res_depth ? temp_depth : res_depth;
if(node->left != NULL){
s.push(node->left);
depth.push(temp_depth + 1);//因为temp_depth得到的是上一层的深度,将子结点压栈后,也将temp_depth+1压栈
}
if(node->right != NULL){
s.push(node->right);
depth.push(temp_depth + 1);//此时压栈的是当前压栈结点的深度
}
}
return res_depth;
}
提交结果:
方法三:广度优先(队列)
利用层次遍历的原理求深度
- 根结点先入队列
- 将队列中结点的子结点入队列,深度+1。遍历队列的同时,遍历过的结点出队列
int maxDepth(TreeNode* root) {
queue<TreeNode*> q;
int depth = 0;
if(root != NULL){
q.push(root);
}
while( !q.empty() ){
TreeNode* node = q.front();
int len = q.size();//得到的是该层结点的个数
depth++;
//一次for循环结束,表示根据遍历队列得到的上层结点,所有的下一层结点已经入队列
for(int i=0; i<len; i++){
TreeNode* temp = q.front();
q.pop();
if(temp->left != NULL){
q.push(temp->left);
}
if(temp->right != NULL){
q.push(temp->right);
}
}
}
return depth;
}
提交结果: