二叉树:二叉树的深度,递归和非递归的方法
普通的DFS递归方法:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return max(left, right) + 1;
}
写到这里,面试官一般会问我们非递归的方法,首先想到是直接遍历,如果是直接遍历那自然就有两种思路,广度优先和深度优先。
先说广度优先,因为是遍历下一层意味着上一层都已遍历,先进先出,采用队列实现:
广度优先遍历模板:
void breadthFirstSearch(Tree root){
queue<Node *> nodeQueue; //使用C++的STL标准模板库
nodeQueue.push(root);
Node *node;
while(!nodeQueue.empty()){
node = nodeQueue.front();
nodeQueue.pop();
cout<<node->data;//遍历根结点
if(node->lchild){
nodeQueue.push(node->lchild); //先将左子树入队
}
if(node->rchild){
nodeQueue.push(node->rchild); //再将右子树入队
}
}
}
/**
* 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*> q;
if(root == NULL)
return 0;
int size = 0;
int level = 0;
q.push(root);
while(!q.empty())
{
size = q.size();
++level;
while(size--)
{
TreeNode *tmp = q.front();
q.pop();
if(tmp->left != NULL)
q.push(tmp->left);
if(tmp->right !=NULL)
q.push(tmp->right);
}
}
return level;
}
};
因为是深度遍历那肯定是先进后出,采用栈实现,然后遍历思路是先遍历当前节点的左子树,没有左子树到情况在遍历右子树:
深度优先遍历模板:
//深度优先遍历
void depthFirstSearch(Tree root){
stack<Node *> nodeStack; //使用C++的STL标准模板库
nodeStack.push(root);
Node *node;
while(!nodeStack.empty()){
node = nodeStack.top();
cout<<node->data;//遍历根结点
nodeStack.pop();
if(node->rchild){
nodeStack.push(node->rchild); //先将右子树压栈
}
if(node->lchild){
nodeStack.push(node->lchild); //再将左子树压栈
}
}
1.递归版本的深度优先:
/**
* 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 maxlevel = 0;
int curlevel = 0;
int maxDepth(TreeNode* root) {
dfs(root);
return maxlevel;
}
void dfs(TreeNode* root)
{
if(root == NULL)
{
maxlevel = max(curlevel, maxlevel);
return;
}
++curlevel;
maxDepth(root->left);
maxDepth(root->right);
--curlevel;
}
};
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) {
stack<pair<TreeNode*, int>> stack;
if(root == NULL)
return 0;
stack.push({
root, 1});
int maxLevel = 1;
while(!stack.empty())
{
pair<TreeNode*, int> temp = stack.top();
stack.pop();
TreeNode* cur = temp.first;
int level = temp.second;
if(cur->left != NULL)
{
stack.push({
cur->left, level + 1});
maxLevel = max(level + 1, maxLevel);
}
if(cur->right !=NULL)
{
stack.push({
cur->right, level + 1});
maxLevel = max(level + 1, maxLevel);
}
}
return maxLevel;
}
};