您的位置:首页 > 其它

【LeetCode 104_二叉树_遍历】Maximum Depth of Binary Tree

2015-07-05 17:18 447 查看


解法一:递归

int maxDepth(TreeNode* root)
{
if (root == NULL)
return 0;

int max_left_Depth = maxDepth(root->left);
int max_right_Depth = maxDepth(root->right);
return max(max_left_Depth, max_right_Depth) + 1;
}


解法二:BFS

int maxDepth(TreeNode* root)
{
if (root == NULL)
return 0;

queue<TreeNode*> node_queue;
node_queue.push(root);

int count = 0;
while (!node_queue.empty()) {
count++;
int len = node_queue.size();
for (int i = 0; i < len; ++i) {
TreeNode *node = node_queue.front();
node_queue.pop();

if (node->left)
node_queue.push(node->left);
if (node->right)
node_queue.push(node->right);
}
}
return count;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: