day16 - 二叉树part03

zqh2023 / 2023-08-24 / 原文

104. 二叉树的最大深度

详解

/**
 * 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) {
        int result = 0;
        queue<TreeNode*> queue_1;
        if(root != NULL) queue_1.push(root);
        while(!empty(queue_1)){
            int size = queue_1.size();
            for(int i=0; i<size; i++){
                TreeNode* node = queue_1.front();
                queue_1.pop();
                if(node->left) queue_1.push(node->left);
                if(node->right) queue_1.push(node->right);
            }
            result++;
        }
        return result;
    }
    */

    //递归
    int search(TreeNode* root, int depth){
        if(root == NULL) return depth;
        int depth_left = search(root->left, depth + 1);
        int depth_right = search(root->right, depth + 1);
        return max(depth_left, depth_right);
    }

    int maxDepth(TreeNode* root) {
        return search(root, 0);
    }
};

 559. N 叉树的最大深度

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    int maxDepth(Node* root) {
        if(root == NULL) return 0;
        int depth = 0;
        for(int i=0; i<root->children.size(); i++){
            depth = max (depth, maxDepth(root->children[i]));
        }
        return depth + 1;
    }
};