1. 程式人生 > >[LeetCode] Diameter of Binary Tree 二叉樹的直徑

[LeetCode] 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 longestpath 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.

這道題讓我們求二叉樹的直徑,並告訴了我們直徑就是兩點之間的最遠距離,根據題目中的例子也不難理解題意。我們再來仔細觀察例子中的那兩個最長路徑[4,2,1,3] 和 [5,2,1,3],我們轉換一種角度來看,是不是其實就是根結點1的左右兩個子樹的深度之和再加1呢。那麼我們只要對每一個結點求出其左右子樹深度之和,再加上1就可以更新結果res了。為了減少重複計算,我們用雜湊表建立每個結點和其深度之間的對映,這樣某個結點的深度之前計算過了,就不用再次計算了,參見程式碼如下:

解法一:

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        if (!root) return 0;
        int res = getHeight(root->left) + getHeight(root->right);
        return max(res, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right)));
    }
    
int getHeight(TreeNode* node) { if (!node) return 0; if (m.count(node)) return m[node]; int h = 1 + max(getHeight(node->left), getHeight(node->right)); return m[node] = h; } private: unordered_map<TreeNode*, int> m; };

上面的方法貌似有兩個遞迴函式,其實我們只需要用一個遞迴函式就可以了,我們再求深度的遞迴函式中順便就把直徑算出來了,而且貌似不用進行優化也能通過OJ,參見程式碼如下:

解法二:

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        int res = 0;
        maxDepth(root, res);
        return res;
    }
    int maxDepth(TreeNode* node, int& res) {
        if (!node) return 0;
        int left = maxDepth(node->left, res);
        int right = maxDepth(node->right, res);
        res = max(res, left + right);
        return max(left, right) + 1;
    }
};

雖說不用進行優化也能通過OJ,但是畢竟還是優化一下好一點啊,參見程式碼如下:

解法三:

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        int res = 0;
        maxDepth(root, res);
        return res;
    }
    int maxDepth(TreeNode* node, int& res) {
        if (!node) return 0;
        if (m.count(node)) return m[node];
        int left = maxDepth(node->left, res);
        int right = maxDepth(node->right, res);
        res = max(res, left + right);
        return m[node] = (max(left, right) + 1);
    }

private:
    unordered_map<TreeNode*, int> m;
};

參考資料: