Leetcode|二叉树的属性|104. 二叉树的最大深度

2021-09-18 15:24:41 浏览数 (1)

1 DFS

代码语言:javascript复制
/**
 * 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;
        int max_depth = max(maxDepth(root->left), maxDepth(root->right));
        return max_depth   1;
    }
};

2 BFS

代码语言:javascript复制
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (!root) return 0;
        queue<TreeNode*> q;
        q.push(root);
        int depth = 0;
        while (!q.empty()) {
            int sz = q.size();
            for (int i=0;i < sz;i  ) {
                TreeNode* e_ptr = q.front(); q.pop();
                if (e_ptr->left) q.push(e_ptr->left);
                if (e_ptr->right) q.push(e_ptr->right);
            }
            depth  ;
        }
        return depth;
    }
};
dfs

0 人点赞