leetcode 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 
          1
         / \
        2   3
       / \     
      4   5    
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.

题目大意:求二叉树中任意两点的最长路径长度。
思路:分别求当前结点的左子树深度和右子树深度。将其相加得到x,并保留x的最大值。

/**
 * 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 Max = 0;
    int dfs(TreeNode* root) {
        if (root == nullptr) return 0;
        int d1 = 0;
        int d2 = 0;
        d1 = dfs(root->left);
        ++d1;
        d2 = dfs(root->right);
        ++d2;
        Max = max(d1 + d2 - 2, Max);
        return max(d1, d2);
    }
    int diameterOfBinaryTree(TreeNode* root) {
        dfs(root);
        return Max;
    }
};
posted on 2018-03-01 09:28  Beserious  阅读(92)  评论(0编辑  收藏  举报