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.
Solution
- 题目意思就是求一二叉树的最大深度,空树的深度定义为0
- 我们可以采用递归的方式来进行,对于空树返回0,否则返回左子树深度+1和右子树深度+1的最大值。(因为子树的深度是父亲的+1)。代码如下:
class Solution {public: int maxDepth(TreeNode* root) { if (!root) return 0; else return max(maxDepth(root->left) + 1,maxDepth(root->right) + 1); }};
- 另外,上述方法其实是采用了DFS(深度优先搜索),在讨论区也看到了利用队列实现的BFS(广度优先搜索),代码如下,侵删。
int maxDepth(TreeNode *root){ if(root == NULL) return 0; int res = 0; queue<TreeNode *> q; q.push(root); while(!q.empty()) { ++ res; for(int i = 0, n = q.size(); i < n; ++ i) { TreeNode *p = q.front(); q.pop(); if(p -> left != NULL) q.push(p -> left); if(p -> right != NULL) q.push(p -> right); } } return res;}