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 @ 2024-11-27 14:34  saulstavo  阅读(20)  评论(0)    收藏  举报