Leetcode 543. Diameter of Binary Tree

本文探讨了LeetCode上543题二叉树直径的解决方案,详细介绍了如何寻找二叉树中两个节点间的最长路径,无论路径是否通过根节点。通过递归深度遍历的方法,结合左右子树深度之和的最大值,实现了高效的求解。代码提供了两种实现方式,包括使用哈希表进行优化。

Leetcode 543. Diameter of Binary Tree

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.

题目大意:
查找二叉树中两个结点间的最长距离,该距离可能不经过根结点。

解题思路:
根据“两个结点间最长距离”在题中的定义,观察可知,如果该距离经过根结点,则两个结点间的最长距离为根结点左右子结点深度之和。如果该距离不经过根结点,则需求出分别以根结点左右子结点的两个结点间的最长距离,再将这三个值进行比较取最大值即可。

代码1:

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        int res = 0;
        depth(root, res);
        return res;
    }
    
    int depth(TreeNode* root, int &res){
        if(!root)
            return 0;
        int left = depth(root->left, res);
        int right = depth(root->right, res);
        res = max(left + right, res);
        return max(left, right) + 1;
    }
};

代码2 (用哈希表储存优化加速):

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        int res = 0;
        depth(root, res);
        return res;
    }
    
    int depth(TreeNode* root, int &res){
        if(!root)
            return 0;
        if(m.count(root))
            return m[root];
        int left = depth(root->left, res);
        int right = depth(root->right, res);
        res = max(left + right, res);
        return m[root] = (max(left, right) + 1);
    }
private:
    unordered_map<TreeNode*, int> m;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值