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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
if (!root)
return ; return max(maxDepth(root->left),
maxDepth(root->right)) + ;
}
};
迭代的解法:
用queue先进先出的特性,按层遍历,最后返回遍历的层数。
class Solution {
public:
int maxDepth(TreeNode *root) {
if (!root) {
return ;
} queue<TreeNode *> nodeQue;
nodeQue.push(root);
int levelNodesCnt;
int depth = ; while (!nodeQue.empty()) {
depth++;
levelNodesCnt = nodeQue.size();
while (levelNodesCnt--) {
if (nodeQue.front()->left)
nodeQue.push(nodeQue.front()->left);
if (nodeQue.front()->right)
nodeQue.push(nodeQue.front()->right);
nodeQue.pop();
}
} return depth;
}
};
附录:
C++ queue使用