543. 二叉树的直径

知识点

不同教材有差异,按照这个理解:层数从0开始,也就是根结点是第0层,树的深度=高度,都是最大层数

问题描述

给你一棵二叉树的根节点,返回该树的 直径 。
二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root 。
两节点之间路径的 长度 由它们之间边数表示。

分析

用该题初步理解树形DP

法一、递归

class Solution {
public:
    int res = 0;
    int solve(TreeNode* root) {
        int x = 0, y = 0;
        if (root == nullptr) {
            return 0;
        }
        x = solve(root->left);
        y = solve(root->right);
        res = max(res, x+y);
        return max(x, y)+1;
    }

    int diameterOfBinaryTree(TreeNode* root) {
        solve(root);
        return res;
    }
};

其中return max(x, y)+1中的+1也可以写到上边的x和y中,即:

class Solution {
public:
    int res = 0;
    int solve(TreeNode* root) {
        int x = 0, y = 0;
        if (root == nullptr) {
            return 0;
        }
        x = solve(root->left) + 1;
        y = solve(root->right) + 1;
        res = max(res, x+y-2);
        return max(x, y);
    }

    int diameterOfBinaryTree(TreeNode* root) {
        solve(root);
        return res;
    }
};
posted @   saulstavo  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示