【Leetcode】【Easy】Maximum Depth of Binary Tree

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.

 

递归解题思路:

①结点为空时,返回0;②当前结点的深度 = max(两个孩子结点各自最大深度)+ 1

 

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int maxDepth(TreeNode *root) {
13         if (!root) 
14             return 0;
15         
16         return max(maxDepth(root->left), 
17                 maxDepth(root->right)) + 1;
18     }
19 };

 

迭代的解法:

用queue先进先出的特性,按层遍历,最后返回遍历的层数。

 

 1 class Solution {
 2 public:
 3     int maxDepth(TreeNode *root) {
 4         if (!root) {
 5             return 0;
 6         }
 7         
 8         queue<TreeNode *> nodeQue;
 9         nodeQue.push(root);
10         int levelNodesCnt;
11         int depth = 0;
12         
13         while (!nodeQue.empty()) {
14             depth++;
15             levelNodesCnt = nodeQue.size();
16             while (levelNodesCnt--) {
17                 if (nodeQue.front()->left)
18                     nodeQue.push(nodeQue.front()->left);
19                 if (nodeQue.front()->right)
20                     nodeQue.push(nodeQue.front()->right);
21                 nodeQue.pop();
22             }
23         }
24         
25         return depth;
26     }
27 };

 

附录:

C++ queue使用

posted @ 2014-11-27 23:22  胡潇  阅读(148)  评论(0编辑  收藏  举报