代码随想录算法训练营day16 | leetcode 104. 二叉树的最大深度、559. N 叉树的最大深度、111. 二叉树的最小深度、222. 完全二叉树的节点个数

104.二叉树的最大深度、111.二叉树的最小深度 见博文

代码随想录算法训练营day15 | leetcode 【二叉树的层序遍历十题】、226. 翻转二叉树、101. 对称二叉树、100. 相同的树、572. 另一棵树的子树

题目链接:559. N 叉树的最大深度-简单

题目描述:

给定一个 N 叉树,找到其最大深度。

最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。

N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。

示例 1:

img

输入:root = [1,null,3,2,4,null,5,6]
输出:3

示例 2:

img

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:5

提示:

  • 树的深度不会超过 1000
  • 树的节点数目位于 [0, 104] 之间。

代码注释处报错了。

代码如下:

/*
// 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;
        // vector<int> subDepth(root->children.size());
        int depth = 0;
        for(int i = 0; i < root->children.size(); ++i){
            // subDepth.push_back(maxDepth(root->children[i]));
            depth = max(depth, maxDepth(root->children[i]));
        }
        // return *max_element(subDepth.begin(), subDepth.end()) + 1;
        return depth + 1;
    }
};

题目链接:222. 完全二叉树的节点个数-简单

题目描述:

给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。

完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

示例 1:

img

输入:root = [1,2,3,4,5,6]
输出:6

示例 2:

输入:root = []
输出:0

示例 3:

输入:root = [1]
输出:1

提示:

  • 树中节点的数目范围是[0, 5 * 104]
  • 0 <= Node.val <= 5 * 104
  • 题目数据保证输入的树是 完全二叉树

进阶:遍历树来统计节点是一种时间复杂度为 O(n) 的简单解决方案。你可以设计一个更快的算法吗?

迭代以及递归时间复杂度均为O(n)

代码如下:

// 时间复杂度:O(n)
// 空间复杂度:O(nlogn)
/**
 * 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 countNodes(TreeNode* root) {
        if(root == NULL) return 0;
        int count = 0;
        count += countNodes(root->left);
        count += countNodes(root->right);
        return count + 1;
    }
};

精简后代码如下:

class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root == NULL) return 0;
        return 1 + countNodes(root->left) + countNodes(root->right);
    }
};
posted @ 2024-03-07 06:38  Humphreyr  阅读(4)  评论(0编辑  收藏  举报