🔥 Day 97 of my 100 Days of Code Problem: Binary Tree Inorder Traversal (LeetCode #94) Problem Description: Given the root of a binary tree, return the inorder traversal of its nodes’ values. Inorder means visiting nodes in this order: Left -> Node -> Right Java Solution: class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); TreeNode current = root; while (current != null || !stack.isEmpty()) { // Reach the leftmost node while (current != null) { stack.push(current); current = current.left; } // Process node current = stack.pop(); result.add(current.val); // Visit right subtree current = current.right; } return result; } } Time Complexity: O(n) Space Complexity: O(n) (for stack in the worst case) #Day97 #LeetCode #100DaysOfCode #Java #BinaryTree #DFS
Inorder Traversal of Binary Tree in Java
More Relevant Posts
-
🔹 Day 47: Find Pivot Index (LeetCode #724) 📌 Problem Statement: Given an array of integers nums, the pivot index is the index where the sum of all numbers to the left is equal to the sum of all numbers to the right. If no such index exists, return -1. If multiple exist, return the leftmost one. ✅ My Approach: I first calculated the total sum of the array, then iterated through each element keeping track of the left sum. At each index, I checked whether left sum == total sum - left sum - current element. If true, that index is the pivot index. 📊 Complexity: Time Complexity: O(n) Space Complexity: O(1) ⚡ Submission Stats: Runtime: 0 ms (Beats 100%) Memory: 45.41 MB (Beats 66.27%) 💡 Reflection: This problem strengthened my understanding of prefix sums and efficient single-pass array traversal. A clean and optimized logic! 💪 #LeetCode #Java #Arrays #PrefixSum #100DaysOfCode #Day47
To view or add a comment, sign in
-
-
#100DaysOfCode – Day 73 String Manipulation Problem: Valid Anagram (LeetCode #242) Task: Given two strings s and t, return true if t is an anagram of s, otherwise false. Example: Input: s = "anagram", t = "nagaram" → Output: true Input: s = "rat", t = "car" → Output: false My Approach:- Method 1 – Sorting Converted both strings into character arrays. Sorted them and compared if equal, they’re anagrams! Time Complexity: O(n log n) Method 2 – Frequency Count (Optimized) Counted occurrences of each character in s and t. If every count matches, it’s a valid anagram. Time Complexity: O(n) | Space: O(1) String problems may look simple, but optimizing from sorting to counting makes a huge difference. Small logic shifts often lead to big performance gains! #100DaysOfCode #Java #ProblemSolving #LeetCode #CodingJourney #takeUforward #DataStructures #Algorithms #StringManipulation #GeeksForGeeks #CodeNewbie
To view or add a comment, sign in
-
-
✅Day38 : Leetcode 35 - Search Insert Position #60DayOfLeetcodeChallenge 🧩 Problem Statement Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. 💡 My Approach I used Binary Search to efficiently find the target position. Initialize low = 0 and high = n - 1. Use a variable ans = n to store the possible insert position. While low <= high, find the mid index. If nums[mid] >= target, store mid as a possible answer and move left. Else, move right by setting low = mid + 1. Return ans at the end. ⏱ Time Complexity O(log n) — because we use Binary Search. 💾 Space Complexity O(1) — only a few variables are used. #BinarySearch #LeetCode #Java #DataStructures #DSA #LeetCodeEasy #SearchInsertPosition
To view or add a comment, sign in
-
-
The Two Pillars: Primitives vs. References Java clearly separates its data types into two main categories: Primitive Types: These hold the actual value directly. They are simple, memory-efficient, and stored in the Stack Memory. They are the 'nuts and bolts' of computation. Numeric: byte, short, int, long (for whole numbers), float, double (for decimals). Character: char (for a single character). Logical: boolean (for true or false). Reference Types (Objects): These do not store the actual data directly. Instead, they store a reference (a memory address) pointing to the object's location in the Heap Memory. Examples include String, Arrays, and any custom class you create (like Scanner or a custom User class). #Java #development #datatypes #aoftwareengineering #OOPs
To view or add a comment, sign in
-
-
LeetCode Question #199 — Binary Tree Right Side View Thrilled to share another Accepted Solution (100% Runtime 🚀) on LeetCode! This problem focuses on Binary Trees — specifically, how to capture the view of a tree from its right side 🌳➡️. I implemented a Modified Pre-Order Traversal (Root → Right → Left) in Java, ensuring that the first node at each level (from the right) gets recorded. 💡 Key Idea: Use recursion with a level tracker — when the current level equals the list size, it means we’re seeing the rightmost node for the first time. Here’s the performance snapshot: ⚙️ Runtime: 0 ms (Beats 100% of Java submissions) 💾 Memory: 42.4 MB Every problem like this sharpens my understanding of tree traversal patterns and depth-first search optimization. #LeetCode #Java #DataStructures #BinaryTree #ProblemSolving #CodingJourney #DSA #100PercentRuntime
To view or add a comment, sign in
-
-
🧠 ThreadLocal — The Hidden Power (and Danger) in Java Ever used ThreadLocal? It’s one of Java’s most mysterious yet powerful tools. It can make your code thread-safe... or cause a silent memory leak 😬 --- 🔹 What it actually does ThreadLocal gives each thread its own copy of a variable. That means no synchronization, no race conditions — just thread-specific data. Perfect for storing things like user sessions, DB connections, or request IDs. Example: private static final ThreadLocal<String> userName = new ThreadLocal<>(); userName.set("Tushar"); System.out.println(userName.get()); // Only visible to current thread --- 🔹 The hidden danger ⚠️ When a thread is reused (like in thread pools), its ThreadLocal value doesn’t automatically reset. If you forget to call remove(), you might end up leaking memory or passing wrong data to the next request. userName.remove(); // Always clean up after use! --- 🔹 Why you should care Spring uses ThreadLocal under the hood for things like RequestContextHolder and TransactionSynchronizationManager. If you understand it, you’ll debug faster and avoid those “it works locally but fails in prod” moments 💥 --- 💬 Your turn: Have you ever faced weird data issues in multi-threaded code? Maybe ThreadLocal was silently involved 😉 Share your story below 👇 #Java #Multithreading #ThreadLocal #BackendDevelopment #SpringBoot #JavaDeveloper #CleanCode
To view or add a comment, sign in
-
(Union of Two Sorted Arrays — Java ) Hey everyone 👋 Today I implemented a program to find the Union of Two Sorted Arrays — while maintaining ascending order and avoiding duplicates. It looks simple at first, but the real challenge is handling duplicates efficiently and merging arrays in one traversal ⚙️ Here’s how I approached it 👇 💡 Concept: When two arrays are sorted, we can use two-pointer technique to compare elements and build the union in sorted order — without using any extra sorting later. ⚙️ Approach: 1️⃣ Initialize two pointers i and j for both arrays. 2️⃣ Compare arr1[i] and arr2[j]. • If one is smaller, add it to the union (if not duplicate). • If both are equal, add once and move both pointers. 3️⃣ Continue until both arrays are traversed. 4️⃣ Handle remaining elements in either array (checking for duplicates). 🧩 Key Takeaway: → Using two-pointer technique avoids extra sorting and reduces redundant comparisons. → Time Complexity: O(N + M) → Space Complexity: O(N + M) (for result storage) This problem helped me understand how small pointer-based optimizations can make merging logic both clean and efficient 🚀 Code is available on my GitHub repo: https://lnkd.in/eT335xuc #Java #DSA #Arrays #ProblemSolving #CodingJourney #TwoPointerTechnique #LearningByDoing #FullStackDeveloper #MCA
To view or add a comment, sign in
-
Day 53/100 Problem Statement : Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. The most significant bit is at the head of the linked list. Input: head = [1,0,1] Output: 5 Solution : https://lnkd.in/g3vuQeUx public int getDecimalValue(ListNode head) { ListNode temp=head; String s=""; while(temp!=null){ s+=temp.val; temp=temp.next; } int ans=Integer.parseInt(s,2); return ans; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
To view or add a comment, sign in
-
Day 43/100 Problem Statement : Given an array nums, you can perform the following operation any number of times: Select the adjacent pair with the minimum sum in nums. If multiple such pairs exist, choose the leftmost one. Replace the pair with their sum. Return the minimum number of operations needed to make the array non-decreasing. An array is said to be non-decreasing if each element is greater than or equal to its previous element (if it exists). Input: nums = [5,2,3,1] Output: 2 Solution : https://lnkd.in/g3Z6NQxN public int minimumPairRemoval(int[] nums) { int length = nums.length - 1; int count = 0; while(length > 0) { boolean increase = true; int minSum = Integer.MAX_VALUE; int minIndex = -1; for(int i = 0; i < length; i++) { if(nums[i] > nums[i + 1]) increase = false; if(nums[i] + nums[i + 1] < minSum) { minSum = nums[i] + nums[i + 1]; minIndex = i; } } if(increase) break; nums[minIndex] = minSum; for(int i = minIndex + 1; i < length; i++) nums[i] = nums[i + 1]; length--; count++; } return count; } #100DaysDSA #100DaysOfCode #Java #Leetcode #Neetcode #Neetcode250 #TUF
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