[每日LeetCode] 543. Diameter of Binary Tree

  |   0 评论   |   624 浏览

原文链接 [每日LeetCode] 543. 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 thelongestpath 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.


思路:本题要求二叉树的直径,这里的直径理解为在二叉树中,任意两个节点间最长的路径长度。本题的逻辑不是很好理解,首先需要考虑最长路径可能没有经过根节点,因此需要考虑以下两个方面的问题:

  • 最长路径经过根节点:那么根节点的左子树的深度和右子树的深度相加就是我们的结果
  • 最长路径没有经过根节点:这个问题就分为两个子问题,分别设置新的根节点为其左子节点和右子节点,然后重复步骤 1

C++代码

/**
 * 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 diameterOfBinaryTree(TreeNode* root) {
        int d = 1;
        diameter(root, d);
        return d - 1;
    }
    int diameter(TreeNode *root, int &d){
        if(!root) return 0;
        int left = diameter(root->left, d);
        int right = diameter(root->right, d);
        d = max(d, left + right + 1);
        return max(left, right) + 1;
    }
};

运行时间:8ms

运行内存:20.1M

评论

发表评论