[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的左右兩個子樹的深度之和呢。那么我們只要對每一個結點求出其左右子樹深度之和,這個值作為一個候選值,然后再對左右子結點分別調用求直徑對遞歸函數,這三個值相互比較,取最大的值更新結果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;
};

 

參考資料:

https://leetcode.com/problems/diameter-of-binary-tree/description/

https://leetcode.com/problems/diameter-of-binary-tree/discuss/101132/java-solution-maxdepth

https://leetcode.com/problems/diameter-of-binary-tree/discuss/101115/543-diameter-of-binary-tree-c_recursive_with-brief-explanation

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM