二叉树:二叉树的深度,递归和非递归的方法
普通的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); //先将左子树入队
}