码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-05 18:31:24      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

解法一:递归

1 int maxDepth(TreeNode* root)
2 {
3     if (root == NULL)
4         return 0;
5 
6     int max_left_Depth = maxDepth(root->left);
7     int max_right_Depth = maxDepth(root->right);
8     return max(max_left_Depth, max_right_Depth) + 1;
9 }

解法二:BFS

 1 int maxDepth(TreeNode* root)
 2 {
 3     if (root == NULL)
 4         return 0;
 5 
 6     queue<TreeNode*> node_queue;
 7     node_queue.push(root);
 8 
 9     int count = 0;
10     while (!node_queue.empty()) {
11         count++;
12         int len = node_queue.size();
13         for (int i = 0; i < len; ++i) {
14             TreeNode *node = node_queue.front();
15             node_queue.pop();
16 
17             if (node->left)
18                 node_queue.push(node->left);
19             if (node->right)
20                 node_queue.push(node->right);
21         }
22     }
23     return count;
24 }

 

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

标签:

原文地址:http://www.cnblogs.com/mengwang024/p/4622652.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!