题意:求一棵二叉树的高度
思路:这里要说一下非递归的写法,就是bfs逐层遍历整棵二叉树,当遍历完一层深度就加一,这里也用到了queue的FIFO特性。
递归:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
return max(maxDepth(root->left) + 1, maxDepth(root->right) + 1);
}
};
非递归:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL)
return 0;
queue<TreeNode *> Q;
Q.push(root);
int curDeepNum = 1;
int depth = 0;
while(!Q.empty()){
TreeNode *curNode = Q.front(); Q.pop();
if(curNode->left != NULL)
Q.push(curNode->left);
if(curNode->right != NULL)
Q.push(curNode->right);
if(--curDeepNum == 0){
depth++;
curDeepNum = Q.size();
}
}
return depth;
}
};