543. Diameter of Binary Tree

来源:互联网 发布:唱歌测音软件 编辑:程序博客网 时间:2024/05/16 13:04

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; *     struct TreeNode *left; *     struct TreeNode *right; * }; */int depth(struct TreeNode * root) {    int l = 0;    int r = 0;    if(root == NULL){        return 0;    }    l = 1 + depth(root->left);    r = 1 + depth(root->right);    return l>r?l:r;}int maxOfThree(int a,int b,int c){    int d = a>b?a:b;    return d>c?d:c;}int diameterOfBinaryTree(struct TreeNode* root) {    if(root == NULL){        return 0;    }    return maxOfThree(diameterOfBinaryTree(root->left),                      diameterOfBinaryTree(root->right),                      depth(root->left)+depth(root->right));}
原创粉丝点击