![](https://i0.wp.com/media.dev.to/cdn-cgi/image/width=1000,height=500,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fo9u50l1mq0nuh9853xc0.png?w=1200&ssl=1)
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; }
}
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; } }
}
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.