leetcode 刷题(求树的直径)

树的直径的定义:

The diameter of a binary tree is the length of thelongest path between any two nodes in a tree. This path may or may not pass through the root.


我首先想到的思路是: 直径必然是两个叶子节点之间的距离的最大值, 怎么求这个最大值呢?

一开始想的是采用穷举, 计算出任何两个叶子节点之间的距离, 求出其中的最大值, 但是这种方法似乎实现起来特别困难; 

不得不转换思路, 转而想, 对于一个节点, 经过这个节点的直径,应该是该节点的左子树的最大深度加上右子树的最大深度。

所以可以依次计算出经过根节点的直径, 经过根节点左孩子的最大直径......., 然后计算出最大值即可。这种实现起来应该比较简单, 毕竟求树的最大深度比较容易。


class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        list<TreeNode* > nodes;
        if (root != NULL) {
            nodes.push_back(root);
        }
        
        int diameter = 0;
        while(!nodes.empty()) {
            TreeNode* node = nodes.front();
            int nd = diameterOfNode(node);
            
            if (nd > diameter) {
                diameter = nd;
            }
            
            nodes.pop_front();
            if (node->left != NULL) {
                nodes.push_back(node->left);
            }
            if (node->right != NULL) {
                nodes.push_back(node->right);
            }
        }
        
        return diameter;
    }
private:
    int depth(TreeNode* root) {			// 计算树的深度
        if (!root) {
            return 0;
        }
        
        if (!root->left && !root->right) {
            return 1;
        }
        
        int ldp = depth(root->left);
        int rdp = depth(root->right);
        
        return (ldp < rdp ? rdp : ldp) + 1;
    }
private:
    int diameterOfNode(TreeNode* root) {	// 计算某个经过某个节点的直径
        if (!root) {
            return 0;
        }
        
        if (!root->left && !root->right) {
            return 0;
        }
        
        return depth(root->left) + depth(root->right);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值