{"id":125,"date":"2025-05-14T12:27:43","date_gmt":"2025-05-14T06:57:43","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=125"},"modified":"2025-05-14T12:30:31","modified_gmt":"2025-05-14T07:00:31","slug":"diameter-of-binary-tree","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/diameter-of-binary-tree\/","title":{"rendered":"Diameter of Binary Tree"},"content":{"rendered":"\n<p>Learn how to calculate the diameter <strong>(longest path)<\/strong> of a binary tree in one pass using recursion. Clear, step-by-step code and explanations perfect for LeetCode practice. You can solve the problem by visiting this <a href=\"https:\/\/leetcode.com\/problems\/diameter-of-binary-tree\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\">Problem Link<\/mark><\/strong><\/a>.<\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-00bd7993-4160-46d1-b931-93e4aa8126a0\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Content:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/diameter-of-binary-tree\/#0-what-the-problem-asks\" style=\"\">What the Problem Asks<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/diameter-of-binary-tree\/#1-how-we%E2%80%99ll-solve-it\" style=\"\">How We\u2019ll Solve It<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/diameter-of-binary-tree\/#2-code-implementation\" style=\"\">Code Implementation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/diameter-of-binary-tree\/#3-step-by-step-explanation\" style=\"\">Step-By-Step Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/diameter-of-binary-tree\/#4-dry-run-on-example\" style=\"\">Dry Run on Example<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/diameter-of-binary-tree\/#5-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-what-the-problem-asks\">What the Problem Asks<\/h2>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>LeetCode 543: Diameter of Binary Tree<\/strong><br>Given a binary tree, find the length of the <strong>diameter <\/strong>of the tree.<br>The <strong>diameter<\/strong> is the number of edges on the longest path between any two nodes in the tree.<\/p>\n<\/blockquote>\n\n\n\n<p><strong>Key point:<\/strong> The longest path might go through the root or any other node.<\/p>\n\n\n\n<p><strong>Example Tree:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"     1\n    \/ \\\n   2   3\n  \/ \\\n 4   5\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">     <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    \/ \\<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">   <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">   <\/span><span style=\"color: #B5CEA8\">3<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">  \/ \\<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">   <\/span><span style=\"color: #B5CEA8\">5<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<p>The longest path is 4 \u2192 2 \u2192 1 \u2192 3, which has 3 edges. So the diameter is <strong>3<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-how-we%E2%80%99ll-solve-it\">How We\u2019ll Solve It<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Calculate Height and Track Diameter at Once<\/strong>\n<ul class=\"wp-block-list\">\n<li>For each node, find the height of its left subtree and right subtree.<\/li>\n\n\n\n<li>A path that passes <strong>through<\/strong> this node has length <code>leftHeight + rightHeight<\/code> (in edges).<\/li>\n\n\n\n<li>Keep a global <code>diameter<\/code> variable and update it whenever <code>leftHeight + rightHeight<\/code> is bigger.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Recursive Height Function<\/strong>\n<ul class=\"wp-block-list\">\n<li>Returns the height of the subtree (in nodes).<\/li>\n\n\n\n<li>While returning, it also updates the diameter.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<p>This way, we only walk the tree <strong>once<\/strong> (O(N) time), and we don\u2019t need extra data structures.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-code-implementation\">Code Implementation<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    diameter = 0  # holds the maximum diameter found\n\n    def calculateHeight(self, root):\n        # Base case: empty tree has height 0\n        if not root:\n            return 0\n\n        # Recursively find heights of left and right subtrees\n        leftHeight = self.calculateHeight(root.left)\n        rightHeight = self.calculateHeight(root.right)\n\n        # Update diameter: path through root uses leftHeight + rightHeight edges\n        self.diameter = max(self.diameter, leftHeight + rightHeight)\n\n        # Return the height of this subtree (in nodes)\n        return 1 + max(leftHeight, rightHeight)\n\n    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -&gt; int:\n        # Initialize diameter and start recursion\n        self.diameter = 0\n        self.calculateHeight(root)\n        return self.diameter\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    diameter = <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">  <\/span><span style=\"color: #6A9955\"># holds the maximum diameter found<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">calculateHeight<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">root<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Base case: empty tree has height 0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">not<\/span><span style=\"color: #D4D4D4\"> root:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Recursively find heights of left and right subtrees<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        leftHeight = <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.calculateHeight(root.left)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        rightHeight = <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.calculateHeight(root.right)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Update diameter: path through root uses leftHeight + rightHeight edges<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.diameter = <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.diameter, leftHeight + rightHeight)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Return the height of this subtree (in nodes)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\"> + <\/span><span style=\"color: #DCDCAA\">max<\/span><span style=\"color: #D4D4D4\">(leftHeight, rightHeight)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">diameterOfBinaryTree<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">root<\/span><span style=\"color: #D4D4D4\">: Optional[TreeNode]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># Initialize diameter and start recursion<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.diameter = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.calculateHeight(root)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.diameter<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-step-by-step-explanation\">Step-By-Step Explanation<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Global Variable <code>diameter<\/code><\/strong>\n<ul class=\"wp-block-list\">\n<li>We store the largest sum of left and right subtree heights (in edges).<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong><code>calculateHeight(root)<\/code><\/strong>\n<ul class=\"wp-block-list\">\n<li>If <code>root<\/code> is <code>None<\/code>, height is 0.<\/li>\n\n\n\n<li>Otherwise:\n<ul class=\"wp-block-list\">\n<li>Compute <code>leftHeight = calculateHeight(root.left)<\/code>.<\/li>\n\n\n\n<li>Compute <code>rightHeight = calculateHeight(root.right)<\/code>.<\/li>\n\n\n\n<li><strong>Update<\/strong> <code>diameter<\/code> with <code>leftHeight + rightHeight<\/code> if it\u2019s larger.<\/li>\n\n\n\n<li>Return <code>1 + max(leftHeight, rightHeight)<\/code> as the subtree height.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong><code>diameterOfBinaryTree(root)<\/code><\/strong>\n<ul class=\"wp-block-list\">\n<li>Reset <code>diameter<\/code> to 0.<\/li>\n\n\n\n<li>Call <code>calculateHeight(root)<\/code>.<\/li>\n\n\n\n<li>Return the final <code>diameter<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<p>This works because <strong>every node<\/strong> gets a chance to consider the path that goes through it. The longest such path anywhere in the tree is our answer.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-dry-run-on-example\">Dry Run on Example<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"       1\n      \/ \\\n     2   3\n    \/ \\\n   4   5\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">       <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">      \/ \\<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">     <\/span><span style=\"color: #B5CEA8\">2<\/span><span style=\"color: #D4D4D4\">   <\/span><span style=\"color: #B5CEA8\">3<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    \/ \\<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">   <\/span><span style=\"color: #B5CEA8\">4<\/span><span style=\"color: #D4D4D4\">   <\/span><span style=\"color: #B5CEA8\">5<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<ol class=\"wp-block-list\">\n<li><code>calculateHeight(4)<\/code> \u2192 left and right are <code>None<\/code> \u2192 heights 0,0 \u2192 diameter = max(0,0) \u2192 returns 1<\/li>\n\n\n\n<li><code>calculateHeight(5)<\/code> \u2192 same \u2192 returns 1<\/li>\n\n\n\n<li>At node 2:\n<ul class=\"wp-block-list\">\n<li>leftHeight=1, rightHeight=1 \u2192 diameter = max(0,1+1)=2<\/li>\n\n\n\n<li>returns 1 + max(1,1)=2<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><code>calculateHeight(3)<\/code> \u2192 returns 1<\/li>\n\n\n\n<li>At node 1:\n<ul class=\"wp-block-list\">\n<li>leftHeight=2, rightHeight=1 \u2192 diameter = max(2,2+1)=3<\/li>\n\n\n\n<li>returns 1 + max(2,1)=3<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<p>Final diameter = <strong>3<\/strong>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-time-amp-space-complexity\">Time &amp; Space Complexity<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong> O(N) \u2014 we visit each node once.<\/li>\n\n\n\n<li><strong>Space:<\/strong> O(H) \u2014 recursion stack up to tree height H (worst-case O(N) for skewed tree, O(log N) for balanced tree).<\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/master-dsa-with-leetcode\" target=\"_blank\" rel=\"noreferrer noopener\">Join our free DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to calculate the diameter (longest path) of a binary tree in one pass using recursion. Clear, step-by-step code and explanations perfect for LeetCode practice. You can solve the problem by visiting this Problem Link. What the Problem Asks LeetCode 543: Diameter of Binary TreeGiven a binary tree, find the length of the diameter<\/p>\n","protected":false},"author":1,"featured_media":127,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[14],"class_list":{"0":"post-125","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-binary-trees"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/05\/diameter-of-a-binary-tree-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/125","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=125"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/125\/revisions"}],"predecessor-version":[{"id":133,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/125\/revisions\/133"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/127"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=125"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=125"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=125"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}