{"id":539,"date":"2017-10-07T00:38:40","date_gmt":"2017-10-07T07:38:40","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=539"},"modified":"2018-04-19T08:32:31","modified_gmt":"2018-04-19T15:32:31","slug":"leetcode-543-diameter-of-binary-tree","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/tree\/leetcode-543-diameter-of-binary-tree\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 543. Diameter of Binary Tree"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 543. Diameter of Binary Tree - \u5237\u9898\u627e\u5de5\u4f5c EP82\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/VuezJmuIyU4?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p><strong>Problem:<\/strong><\/p>\n<p>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\u00a0<b>longest<\/b>\u00a0path between any two nodes in a tree. This path may or may not pass through the root.<\/p>\n<p><b>Example:<\/b><br \/>\nGiven a binary tree<\/p>\n<pre>          1\r\n         \/ \\\r\n        2   3\r\n       \/ \\     \r\n      4   5    \r\n<\/pre>\n<p>Return\u00a0<b>3<\/b>, which is the length of the path [4,2,1,3] or [5,2,1,3].<\/p>\n<p><b>Note:<\/b>\u00a0The length of path between two nodes is represented by the number of edges between them.<\/p>\n<p>&nbsp;<\/p>\n<p><strong>Idea:<\/strong><\/p>\n<p>Recursion<\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/10\/543-ep82.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-543\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/10\/543-ep82.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/10\/543-ep82.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/10\/543-ep82-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/10\/543-ep82-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/10\/543-ep82-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p><strong>Solution1:<\/strong><\/p>\n<p>C++<\/p>\n<pre class=\"lang:c++ decode:true\">class Solution {\r\npublic:\r\n    int diameterOfBinaryTree(TreeNode* root) {        \r\n        ans_ = 0;\r\n        LP(root);\r\n        return ans_;\r\n    }\r\nprivate:\r\n    int ans_;\r\n    int LP(TreeNode* root) {\r\n        if (!root) return -1;\r\n        int l = LP(root-&gt;left) + 1;\r\n        int r = LP(root-&gt;right) + 1;\r\n        ans_ = max(ans_, l + r);\r\n        return max(l, r);\r\n    }\r\n};<\/pre>\n<p><strong>Solution 2: passed 101\/106\u00a0<span style=\"color: #ff0000;\">TLE<\/span><\/strong><\/p>\n<p>C++ \/ Floyd-Warshall<\/p>\n<pre class=\"lang:default decode:true \">\/\/ Author: Huahua\r\n\/\/ State: 101\/106 passed TLE\r\nclass Solution {\r\npublic:\r\n    int diameterOfBinaryTree(TreeNode* root) {\r\n        if (!root) return 0;        \r\n        edges_.clear();\r\n        int n = 0;\r\n        buildGraph(root, n, -1);        \r\n        vector&lt;vector&lt;int&gt;&gt; d(n, vector&lt;int&gt;(n, n));\r\n        for (int i = 0; i &lt; n; ++i) d[i][i] = 0;\r\n        for (const auto&amp; pair : edges_)\r\n            d[pair.first][pair.second] = 1;\r\n        \r\n        for (int k = 0; k &lt; n; ++k)\r\n            for (int i = 0; i &lt; n; ++i)\r\n                for (int j = 0; j &lt; n; ++j)\r\n                    d[i][j] = min(d[i][j], d[i][k] + d[k][j]);\r\n        \r\n        int ans = INT_MIN;\r\n        for (int i = 0; i &lt; n; ++i)\r\n                for (int j = 0; j &lt; n; ++j) {\r\n                    if (d[i][j] == n) continue;\r\n                    ans = max(ans, d[i][j]);\r\n                }\r\n        return ans;\r\n    }\r\n    \r\nprivate:\r\n    void buildGraph(TreeNode* node, int&amp; id, int pid) {\r\n        if (!node) return; \r\n        int node_id = id++;\r\n        if (pid &gt;= 0) {\r\n            edges_.emplace_back(node_id, pid);\r\n            edges_.emplace_back(pid, node_id);            \r\n        }\r\n        buildGraph(node-&gt;left, id, node_id);\r\n        buildGraph(node-&gt;right, id, node_id);\r\n    }            \r\n    vector&lt;pair&lt;int,int&gt;&gt; edges_;\r\n};<\/pre>\n<p><strong>Solution 3:<\/strong><\/p>\n<p>Simulate recursion with a stack. We also need to track the return value of each node.<\/p>\n<p>Python<\/p>\n<pre class=\"lang:python decode:true  \">\"\"\"\r\nAuthor: Huahua\r\nRuntime: 82 ms\r\n\"\"\"\r\nclass Solution:\r\n    def diameterOfBinaryTree(self, root):\r\n        if not root: return 0\r\n        d = {None: -1}\r\n        s = [root]\r\n        ans = 0\r\n        while s:\r\n            node = s[-1]\r\n            if node.left in d and node.right in d:\r\n                s.pop()\r\n                l = d[node.left] + 1\r\n                r = d[node.right] + 1\r\n                ans = max(ans, l + r)\r\n                d[node] = max(l, r)\r\n            else:\r\n                if node.left: s.append(node.left)\r\n                if node.right: s.append(node.right)\r\n        return ans<\/pre>\n<p>&nbsp;<\/p>\n<p>C++<\/p>\n<pre class=\"lang:default decode:true \">\/\/ Author: Huahua\r\n\/\/ Runtime: 15 ms\r\nclass Solution {\r\npublic:\r\n    int diameterOfBinaryTree(TreeNode* root) {        \r\n        if (!root) return 0;\r\n        int ans = 0;\r\n        unordered_map&lt;TreeNode*, int&gt; d{{nullptr, -1}};        \r\n        stack&lt;TreeNode*&gt; s;\r\n        s.push(root);\r\n        while (!s.empty()) {\r\n            TreeNode* node = s.top();            \r\n            if (d.count(node-&gt;left) &amp;&amp; d.count(node-&gt;right)) {                \r\n                int l = d[node-&gt;left] + 1;\r\n                int r = d[node-&gt;right] + 1;\r\n                ans = max(ans, l + r);\r\n                d[node] = max(l, r);\r\n                \/\/ children's results will never be used again, safe to delete here.\r\n                if (node-&gt;left) d.erase(node-&gt;left);\r\n                if (node-&gt;right) d.erase(node-&gt;right);\r\n                s.pop();\r\n            } else {\r\n                if (node-&gt;left) s.push(node-&gt;left);\r\n                if (node-&gt;right) s.push(node-&gt;right);\r\n            }\r\n        }\r\n        return ans;\r\n    }\r\n};<\/pre>\n<p>&nbsp;<\/p>\n<p><strong>Related Problems:<\/strong><\/p>\n<ul>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/tree\/leetcode-687-longest-univalue-path\/\">[\u89e3\u9898\u62a5\u544a] LeetCode 687. Longest Univalue Path<\/a><\/li>\n<li><a href=\"http:\/\/zxi.mytechroad.com\/blog\/graph\/leetcode-743-network-delay-time\/\">\u82b1\u82b1\u9171 LeetCode 743. Network Delay Time<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Problem: Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[45],"tags":[17,87],"class_list":["post-539","post","type-post","status-publish","format-standard","hentry","category-tree","tag-recursion","tag-shortest-path","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/539","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=539"}],"version-history":[{"count":10,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/539\/revisions"}],"predecessor-version":[{"id":2588,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/539\/revisions\/2588"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=539"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=539"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=539"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}