DEV Community

Tanuja V
Tanuja V

Posted on • Edited on

3 1 1 3 2

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 if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs