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.

Example:
Given a binary tree 

 
  

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

求二叉树的直径,直径就是两点之间的最远距离,其实就是节点的左子树深度和右子树深度之和,比如1的左子树深度=2 右子树深度为1,直径=2+1 = 3。所以只需要对每一个节点求出其左右子树深度之和,取所有节点最大的值即可。

1. 

int depthOfNode(TreeNode *root){
    if(!root) return 0;
    return max(depthOfNode(root->left),depthOfNode(root->right)) +1;
}
int diameterOfBinaryTree(TreeNode* root) {
    if(!root) return 0;
    int ans = depthOfNode(root->left)+depthOfNode(root->right);
    return max(ans,max(diameterOfBinaryTree(root->left),diameterOfBinaryTree(root->right)));
}

Runtime:48ms;Memory:35.5MB

2. 优化一下,在求深度的同时记录最大值

int maxOfDepth(int& ans, TreeNode* root){
    if(!root) return 0;
    int l = maxOfDepth(ans,root->left);
    int r = maxOfDepth(ans,root->right);
    ans = max(l+r,ans);
    return max(l,r)+1;
}
int diameterOfBinaryTree2(TreeNode* root) {
    int ans =0;maxOfDepth(ans,root);
    return ans;
}

Runtime:8ms, faster than 96.74% ;Memory:19.8MB, less than 70.72%

 

test:

int main(int argc, const char * argv[]) {
    TreeNode *ln = new TreeNode(1);
    TreeNode *l = new TreeNode(2);
    l->left =new TreeNode(3);   
    l->right =new TreeNode(4);
    TreeNode *r = new TreeNode(5);
    ln->left = l; ln->right = r;
    cout<

 

你可能感兴趣的:(oj)