二叉树的深度

  • 二叉树的深度为:根节点到叶子节点的路径上的节点数。

层序遍历-求最大深度

  1. class Solution {
  2. public:
  3. int maxDepth(TreeNode* root) {
  4. if (root == NULL) return 0;
  5. int depth = 0;
  6. queue<TreeNode*> que;
  7. que.push(root);
  8. while(!que.empty()) {
  9. int size = que.size();
  10. depth++; // 记录深度
  11. for (int i = 0; i < size; i++) {
  12. TreeNode* node = que.front();
  13. que.pop();
  14. if (node->left) que.push(node->left);
  15. if (node->right) que.push(node->right);
  16. }
  17. }
  18. return depth;
  19. }
  20. };

层序遍历-求最小深度

  1. class Solution {
  2. public:
  3. int minDepth(TreeNode* root) {
  4. if (root == NULL) return 0;
  5. int depth = 0;
  6. queue<TreeNode*> que;
  7. que.push(root);
  8. while(!que.empty()) {
  9. int size = que.size();
  10. depth++; // 记录最小深度
  11. for (int i = 0; i < size; i++) {
  12. TreeNode* node = que.front();
  13. que.pop();
  14. if (node->left) que.push(node->left);
  15. if (node->right) que.push(node->right);
  16. // 当左右孩子都为空的时候,说明是最低点的一层了,退出
  17. if (!node->left && !node->right) {
  18. return depth;
  19. }
  20. }
  21. }
  22. return depth;
  23. }
  24. };

递归写法-求最小深度

  1. class Solution {
  2. public:
  3. int minDepth(TreeNode* root) {
  4. if (root == NULL) return 0;
  5. if (root->left == NULL && root->right != NULL) {
  6. return 1 + minDepth(root->right);
  7. }
  8. if (root->left != NULL && root->right == NULL) {
  9. return 1 + minDepth(root->left);
  10. }
  11. return 1 + min(minDepth(root->left), minDepth(root->right));
  12. }
  13. };