🚀 Day 112 of #LeetCode Challenge! Problem: Diameter of Binary Tree 💡 My Approach: The diameter of a binary tree is the longest path between any two nodes (may or may not pass through the root). The trick is to calculate the height of each subtree while keeping track of the maximum left + right path encountered. Use a helper function height() that: Recursively computes left and right subtree heights. Updates the global diameter as the maximum sum of left and right heights. ✨ Example: Input: [1,2,3,4,5] Output: 3 Explanation: The longest path is [4,2,1,3] or [5,2,1,3] ⏱ Time Complexity: O(N) — visit every node once 💾 Space Complexity: O(H) — recursive stack (H = height of tree) 🌱 Key Insight: At each node, the longest path through it is leftHeight + rightHeight. The overall diameter is the maximum of all such paths. 👨💻 GitHub Link: https://lnkd.in/dvUDMZUC #LeetCode #BinaryTree #Recursion #TreeTraversal #DSA #CodingChallenge #C++ #Day112
How to find the diameter of a binary tree using recursion
More Relevant Posts
-
🚀 Day 124 of #LeetCode Challenge! Problem: Binary Tree Inorder Traversal 💡 My Approach: The goal is to perform an inorder traversal of a binary tree — visiting nodes in the order: Left → Root → Right. Here’s how I implemented it: Use recursion to traverse the tree. Start from the root node. Recursively visit the left subtree, then record the root value, and finally traverse the right subtree. This ensures all nodes are visited in sorted order for a BST. ✨ Example Input: [1, null, 2, 3] Output: [1, 3, 2] 🧠 Key Idea Inorder traversal naturally retrieves nodes in ascending order if the tree is a Binary Search Tree (BST). ⏱ Complexity TypeValueTimeO(N) — each node visited onceSpaceO(H) — recursion stack (H = height of tree) 📎 GitHub Link: https://lnkd.in/gBgJShhT #LeetCode #BinaryTree #InorderTraversal #Recursion #DSA #C++ #ProblemSolving #CodingChallenge #Day124
To view or add a comment, sign in
-
-
🚀 Day 115 of #LeetCode Challenge! Problem: Symmetric Tree 🌳 Concept: Check whether a binary tree is a mirror of itself (i.e., symmetric around its center). 💡 My Approach: Use recursion to compare left and right subtrees. A tree is symmetric if: Left subtree of left node matches right subtree of right node Right subtree of left node matches left subtree of right node Base cases: Both nodes NULL → symmetric ✅ One NULL and one not → not symmetric ❌ Values must match ✨ Example: Input: [1,2,2,3,4,4,3] Output: true ⏱ Time Complexity: O(N) — visiting all nodes 📦 Space Complexity: O(H) — recursion stack (H = height of tree) 📌 Key Insight: This is a classic mirror check — left's left must mirror right's right! 👨💻 GitHub Link: https://lnkd.in/gid6xjvn #LeetCode #BinaryTree #Recursion #SymmetricTree #MirrorTree #DSA #ProblemSolving #C++ #CodingChallenge #Day114
To view or add a comment, sign in
-
-
🚀 Day 123 of #LeetCode Challenge! Problem: Convert Sorted Array to Binary Search Tree 💡 My Approach: The task is to convert a sorted array into a height-balanced BST — meaning the depth of the two subtrees of every node should not differ by more than one. Here’s how I approached it: Pick the middle element of the array as the root (ensures balance). Recursively build the left subtree from the left half. Recursively build the right subtree from the right half. This method ensures the tree is balanced and follows the BST property (left < root < right). 🧠 Key Idea The midpoint of the current range always becomes the root, making the BST height-balanced naturally. ✨ Example Input: nums = [-10, -3, 0, 5, 9] Output: A balanced BST like: 0 / \ -3 9 / / -10 5 ⏱ Complexity TypeValueTimeO(N) — each element is processed onceSpaceO(log N) — recursion stack (for balanced BST) 📎 GitHub Link: https://lnkd.in/gDkzKT6A #LeetCode #BinarySearchTree #Recursion #C++ #ProblemSolving #DSA #Day123 #CodingChallenge
To view or add a comment, sign in
-
-
🚀 Day 114 of #LeetCode Challenge! Problem: Symmetric Tree 🌳 Concept: Check whether a binary tree is a mirror of itself (i.e., symmetric around its center). 💡 My Approach: Use recursion to compare left and right subtrees. A tree is symmetric if: Left subtree of left node matches right subtree of right node Right subtree of left node matches left subtree of right node Base cases: Both nodes NULL → symmetric ✅ One NULL and one not → not symmetric ❌ Values must match ✨ Example: Input: [1,2,2,3,4,4,3] Output: true ⏱ Time Complexity: O(N) — visiting all nodes 📦 Space Complexity: O(H) — recursion stack (H = height of tree) 📌 Key Insight: This is a classic mirror check — left's left must mirror right's right! 👨💻 GitHub Link: https://lnkd.in/grXFRA2i #LeetCode #BinaryTree #Recursion #SymmetricTree #MirrorTree #DSA #ProblemSolving #C++ #CodingChallenge #Day114
To view or add a comment, sign in
-
-
🚀 Day 117 of #LeetCode Challenge! Problem: Univalued Binary Tree 💡 My Approach: We need to check if all nodes in the binary tree have the same value. 🔍 Steps: Store the root value as the target value DFS through every node If any node's value ≠ root value → return false If traversal completes with no mismatch → return true ✅ 📌 Key Idea: A binary tree is univalued if every node contains the same value. ✨ Example: Input: [1,1,1,1,1,null,1] Output: true Input: [2,2,2,5,2] Output: false ⏱ Time Complexity: O(N) — every node is checked 💾 Space Complexity: O(H) — recursion stack (H = tree height) 👨💻 GitHub Link: https://lnkd.in/g3xFQpAm #LeetCode #BinaryTree #DFS #Recursion #DSA #Day117 #C++ #ProblemSolving #CodingChallenge
To view or add a comment, sign in
-
-
🚀 Day 127 of #LeetCode Challenge! Problem: Binary Tree Level Order Traversal 💡 My Approach: This problem involves traversing the binary tree level by level — also known as Breadth-First Search (BFS) traversal. Here’s the step-by-step breakdown: Use a queue to store nodes level by level. For each level, store all node values in a temporary list. Push their left and right children into the queue. After finishing one level, add it to the result vector. ✨ Example Input: [3,9,20,null,null,15,7] Output: [[3], [9,20], [15,7]] 🧠 Key Idea This traversal captures the hierarchical structure of the tree perfectly — often used in problems involving level-based processing, like Zigzag traversal or average of levels. ⏱ Complexity TypeValueTimeO(N) — each node visited onceSpaceO(N) — for queue and result storage 📎 GitHub Link: https://lnkd.in/gntMrKbU #LeetCode #BinaryTree #BFS #LevelOrderTraversal #DSA #ProblemSolving #C++ #CodingChallenge #100DaysOfCode #Day127
To view or add a comment, sign in
-
-
🚀 Day 125 of #LeetCode Challenge! Problem: Binary Tree Preorder Traversal 💡 My Approach: The goal is to perform a preorder traversal of a binary tree — visiting nodes in the order: Root → Left → Right Here’s the step-by-step logic: Start from the root node. Visit (record) the root value first. Recursively traverse the left subtree, then the right subtree. Store values in a vector as you go. ✨ Example Input: [1, null, 2, 3] Output: [1, 2, 3] 🧠 Key Idea Preorder traversal is useful when you need to copy or serialize a tree — it captures the structure starting from the root. ⏱ Complexity TypeValueTimeO(N) — each node visited onceSpaceO(H) — recursion stack (H = height of tree) 📎 GitHub Link: https://lnkd.in/gZ6GeXzm #LeetCode #BinaryTree #PreorderTraversal #Recursion #DSA #C++ #ProblemSolving #CodingChallenge #Day125
To view or add a comment, sign in
-
-
💻 Day 47 of #50DaysOfLeetCode Challenge 🚀 Problem: Binary Tree Maximum Path Sum (Leetcode 124) The goal was to find the maximum path sum in a binary tree — where the path can start and end at any node, not just the root. 🌲 🧠 Approach: I solved it using postorder traversal (Left → Right → Root). At every node, I calculated: 1️⃣ bothpaths → path passing through root (left + right + root) 2️⃣ bestpath → best path going downward from root (max of left or right + root) 3️⃣ onlyroot → when only the root node is part of the path At each step, I updated a global maxsum with the best of these three values. This way, every node contributed the maximum possible sum considering all cases. 🧩 Key Takeaway: 👉 Always think in terms of "What value should I return to parent?" vs "What value should I update globally?" 👉 Binary tree recursion becomes intuitive once you separate these two thoughts.
To view or add a comment, sign in
-
-
🚀 Day 93 of My #100DaysOfCode Challenge! Today, I explored one of the most fundamental and elegant problems in Binary Trees — the Diameter of a Binary Tree 🌳 using C++. The goal of this problem is to find the longest path between any two nodes in a binary tree. This path may or may not pass through the root. To solve it efficiently, I used recursion and the concept of tree height. 💡 What I Learned: 🔹 Height Function: The height of a node is 1 + max(height(left), height(right)). I built a recursive function height(TreeNode* root) that returns the height of any subtree. 🔹 Diameter Function: For each node, I calculated three possible diameters: Diameter of the left subtree Diameter of the right subtree Diameter passing through the current node (left height + right height) The maximum of these three gives the current diameter. 🔹 Key Insight: This approach uses recursion twice (once for height and once for diameter), which makes it O(N²) — a good starting point for understanding the logic before optimizing it to O(N) with a single traversal. 🧠 Concepts Strengthened: Recursive Tree Traversal Depth & Height calculation Problem decomposition using subproblems Understanding tree structure visualization 🌱 Slowly mastering trees — one recursive function at a time! Next step: Optimize the diameter function for O(N) time complexity using a single DFS call. #Day93 #100DaysOfCode #CPlusPlus #DSA #BinaryTree #Recursion #ProblemSolving #CodingJourney #LeetCode
To view or add a comment, sign in
-
-
🚀 Day 122 of #LeetCode Challenge! Problem: Subtree of Another Tree 💡 My Approach: The goal is to check whether one tree (subRoot) is a subtree of another (root). Here’s how I approached it: Traverse the main tree (root) recursively. At each node, check if the subtree starting there is identical to subRoot. If not, keep checking in the left and right subtrees. For the comparison, a helper function isSameTree() ensures both trees have identical structure and node values. 🧠 Key Idea A tree subRoot is a subtree of root if there exists a node in root such that the subtree rooted at that node is structurally identical to subRoot. ✨ Example Input: root = [3,4,5,1,2] subRoot = [4,1,2] Output: ✅ true Explanation: The subtree starting at node 4 in root matches subRoot. ⏱ Complexity TypeValueTimeO(M × N) — for each node in root, we may compare with all nodes in subRootSpaceO(H) — recursion stack (H = height of the tree) 📎 GitHub Link: https://lnkd.in/gv3w8RFe #LeetCode #BinaryTree #Recursion #C++ #ProblemSolving #Day122 #CodingChallenge
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development