您的位置:首页 > 其它

LeetCode 104. Maximum Depth of Binary Tree

2016-02-11 11:04 295 查看
题意:求一棵二叉树的高度

思路:这里要说一下非递归的写法,就是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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: