我的算法6

题目地址https://leetcode.com/problems/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.

* 我的代码*

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

    int high_of_binary_tree(TreeNode* root){
        if(root==NULL) return 0;
        int a=high_of_binary_tree(root->left);
        int b=high_of_binary_tree(root->right);
        int c=a>b?a:b;
        return c+1;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        if(root==NULL) return 0;
        int a=high_of_binary_tree(root->left);
        int b=high_of_binary_tree(root->right);
        int c=diameterOfBinaryTree(root->left);
        int d=diameterOfBinaryTree(root->right);
        if(d>c) c=d;
        if(a+b>c) c=a+b;
        return c;
    }
};

解题思路
将最长路的可能出现情况分为三种,第一种是经过顶点,第二种是全部在左子树中,第三种是全部在右子树中。对于第一种,其长度显然为左子树高度加右子树高度,而第二、三种,可以递归得到。
最后,取三者中最大值即可。复杂度为O(n^2)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值