LeetCode – 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.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its depth = 3.

 

解题:

     深度优先搜索方式,分别找到左右子树最大的深度+1即可;广度优先搜索,逐层遍历找到最大层数返回。 

实现

  • DFS, 空间复杂度O(N)    时间复杂度 O(N)
          
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) {return 0;}
        return 1 + max( maxDepth(root->left), maxDepth(root->right));
    }
};

实现:

  • BFS  空间复杂度O(N)    时间复杂度 O(N)
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
/*
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) {return 0;}
        return 1 + max( maxDepth(root->left), maxDepth(root->right));
    }
};*/

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root){
            return 0;
        }
        queue<TreeNode*> q;
        int depth=0;
        q.push(root);
        while(!q.empty()){
            depth ++;
            int level_size = q.size();
            for (int i=0; i<level_size; i++){
                TreeNode *node = q.front();
                q.pop();
                if (node->left){
                    q.push(node->left);
                }
                if (node->right){
                    q.push(node->right);
                }
            }
        }
        return depth;
    }
};

Be First to Comment

发表回复