543. Diameter of Binary Tree

本文深入探讨了二叉树直径的计算问题,提供三种不同的解决方案,包括直接计算、使用哈希表避免重复计算和在求高度过程中计算直径。通过递归和遍历技巧,有效地解决了距离最远节点对的问题。

Description:
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Analysis:
求二叉树的直径,直径是指二叉树中距离最远的两个结点的距离,不是结点个数。

二叉树问题:都是(先序、中序、后序)遍历+递归,组合拳解决。
开始以为距离最远一定会过根结点,其实不一定。

Solution1:

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        if (root == NULL)
            return 0;
        int cur = 0;
        int left = 0, cur_left = 0;
        int right = 0, cur_right = 0;
        // 相当于一根火柴,左边的起点代表这一根
        left = GetMaxHeight(root->left);
        right = GetMaxHeight(root->right);
        cur = left + right;

        cur_left = diameterOfBinaryTree(root->left);
        cur_right = diameterOfBinaryTree(root->right);
        
        return max(cur, max(cur_left, cur_right));
    }
    int GetMaxHeight(TreeNode* root) {
        if (root == NULL)
            return 0;
        int left = GetMaxHeight(root->left);
        int right = GetMaxHeight(root->right);
        return left > right ? (left + 1) : (right + 1);
    }
};

Solution2:
解法1中会在求高度时,会有重复的求解,可以用一个map保存已经求出的高度。

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        if (root == NULL)
            return 0;
        int cur = GetMaxHeight(root->left) + GetMaxHeight(root->right);
        return max(cur, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right)));
    }
    int GetMaxHeight(TreeNode* root) {
        if (root == NULL)
            return 0;
        if (mp.find(root) != mp.end()) {
            return mp[root];
        }

        int left = GetMaxHeight(root->left);
        int right = GetMaxHeight(root->right);
        int ret = max(left, right) + 1;
        mp[root] = ret;
        return ret;
    }
private:
    unordered_map<TreeNode *, int> mp;
};

Solution3:
在求树的高度时求出直径,同时比较每棵子树的直径和当前最大直径。

class Solution {
private:
    int diameter = 0;
public:
    int diameterOfBinaryTree(TreeNode* root) {
        GetMaxHeight(root);
        return diameter;
    }
    int GetMaxHeight(TreeNode* root) {
        if (root == NULL)
            return 0;
        int left = GetMaxHeight(root->left);
        int right = GetMaxHeight(root->right);
        // left+right 相当于一根火柴,左边的起点代表这一根
        diameter = max(diameter, left + right);
        return max(left, right) + 1;
    }
};

Reference:
[1] https://my.oschina.net/liyurong/blog/1503784

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值