Flatten Binary Tree to Linked List | LeetCode | Java

Approach 1 : Using DFS

class Solution { TreeNode prevNode = null; public void flatten(TreeNode root) { if(root==null) return; flatten(root.right); flatten(root.left); root.right = prevNode; root.left = null; prevNode = root; }
}
Enter fullscreen mode
Exit fullscreen mode

Approach 2 : Using Stack (BFS)

class Solution { public void flatten(TreeNode root) { if(root==null) return; Stack<TreeNode> stack = new Stack<>(); stack.add(root); while(!stack.isEmpty()){ TreeNode currentNode = stack.pop(); if(currentNode.right!=null) stack.push(currentNode.right); if(currentNode.left!=null) stack.push(currentNode.left); if(!stack.isEmpty()) currentNode.right = stack.peek(); currentNode.left = null; } }
}
Enter fullscreen mode
Exit fullscreen mode

Thanks for reading🥰.
Feel free to comment🖌️ and like the post💓
Follow for more 🤝 && Happy Coding🚀👩‍💻

Don’t forget to check-out my other socials😍:
Github
Hashnode
Medium
Twitter(X)


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
100% one of the best cloud data storage solutions | cloudy storage. How to install docker and docker compose on ubuntu 20. Privacy, cookie & data policy.