543. Diameter of Binary Tree

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.

Thoughts

返回二叉树任意两点所形成的路径中长度最长的路径的长度,长度为路径中边的数目。二叉树=>分治。对于给定的结点node,分别有三种情况:diameter在左子树,diameter在右子树以及diameter穿过当前结点。如果只存储和返回当前结点所在子树的diameter,则不能知道left diameter本身到底是上面的哪三种构成的,而且即使知道了也不能直接利用(只有当node.left是diameter终点时才能直接和当前点加起来形成新的diameter)。因此需要额外global变量res存最终结果。问的是path长度,因此return时+1用来计入从cur往上申出的边。

Code

/*
 * @lc app=leetcode id=543 lang=cpp
 *
 * [543] Diameter of Binary Tree
 */

// @lc code=start
/**
 * 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 res = 0;
    int dfs(TreeNode *cur) {
        if (cur == nullptr) return 0;
        int l = dfs(cur->left);
        int r = dfs(cur->right);
        res = max(res, l + r);
        return max(l, r) + 1;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        dfs(root);
        return res;
    }
};
// @lc code=end

Analysis

时间复杂度O(n).

Ver.2

Iterative solution based on post-order traversal. diameters记录两个值, 左中右连起来的长度和只有左中或右中的长度最大值. 前者用于算最长的可能值, 后者用于最为子结果喂给父节点.

Last updated

Was this helpful?