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

104. Maximum Depth of Binary Tree

时间:2016-06-18 20:01:22      阅读:324      评论:0      收藏:0      [点我收藏+]

标签:

1. 问题描述

Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Tags: Tree Depth-first Search
Similar Problems: (E) Balanced Binary Tree (E) Minimum Depth of Binary Tree
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

2. 解题思路

  • 可以利用递归方式实现,但在LeetCode上运行超时,考虑使用循环方式实现
  • 利用队列,逐层计算:

3. 代码

 1 class Solution {
 2 public:
 3     //非递归方法(利用队列实现)
 4     int maxDepth(TreeNode* root) 
 5     {
 6         if (NULL == root)
 7         {
 8             return 0;
 9         }
10         std::queue<TreeNode *> tQue;
11         tQue.push(root);
12         int ndepth = 0;
13         while (!tQue.empty())
14         {
15             ndepth++;
16             int nSize = tQue.size();            
17             for (int i=0; i<nSize; i++)
18             {
19                 TreeNode *pCur = tQue.front();
20                 tQue.pop();
21                 if (NULL != pCur->left)
22                 {
23                     tQue.push(pCur->left);
24                 }
25                 if (NULL != pCur->right)
26                 {
27                     tQue.push(pCur->right);
28                 }
29             }
30         }
31         return ndepth;
32     }
33     //递归实现(运行时间超时)
34     int maxDepth_1(TreeNode* root) 
35     {
36         if (NULL == root)
37         {
38             return 0;
39         }
40         return 1+(maxDepth(root->left)>maxDepth(root->right) ? maxDepth(root->left):maxDepth(root->right));
41     }
42 };

 

4. 反思

  •  思路类似树的广度优先遍历

104. Maximum Depth of Binary Tree

标签:

原文地址:http://www.cnblogs.com/whl2012/p/5596695.html

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