树的层级遍历?用队列实现层次遍历,所以不需要另写一个helper函数递归
1. 层级遍历 无意的ac 误打误撞的
看了题解面试题55 - I. 二叉树的深度(后序遍历、层序遍历,清晰图解) - 二叉树的深度 - 力扣(LeetCode) (leetcode-cn.com),仿照着写了c++,但是这里我res初始化是-1,最后也ac了,看了下代码,区别是判断语句
/**
* 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) {
queue<TreeNode*> que;
que.push(root);
int res= -1;
while(!que.empty()){
queue<TreeNode*> tmp;
while( !que.empty()){
TreeNode* head = que.front();
que.pop();
if(head)tmp.push(head->left);
if(head)tmp.push(head->right);
}
que = tmp;
res ++;
}
return res;
}
};
就是如下的判断语句:1是判断head为空而不是判断左右子节点为空,2是res可以初始化为-1这样做最开始不用判断root是否为空,而且当root为空的时候也能返回正确答案。
2. 常规解法-层级遍历
这里如果判断的是left和right,就需要先判断root是不是空
/**
* 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*> que;
que.push(root);
int res= 0;
while(!que.empty()){
queue<TreeNode*> tmp;
while( !que.empty()){
TreeNode* head = que.front();
que.pop();
if(head->left)tmp.push(head->left);
if(head->right)tmp.push(head->right);
}
que = tmp;
res ++;
}
return res;
}
};
2. 常规解法-深度优先搜索
/**
* 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 max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};