我的算法6

来源:互联网 发布:综合评价算法 编辑:程序博客网 时间:2024/04/29 07:06

题目地址: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