Super easy understand AC solution using queue......


  • 1
    U
    public class Solution {// add nodes to a queue in preorder way, then link all the nodes
    Queue<TreeNode> q= new LinkedList<TreeNode>();
    public void flatten(TreeNode root) {
        preorder(root);
        while(q.size()!=0){
            TreeNode temp= q.poll();
            if(q.size()==0){
                temp.right=null;
                temp.left=null;
            }
            else{
                temp.right=q.peek();
                temp.left=null;
            }
        }
        
    }
    private void preorder(TreeNode root){
        if(root==null) 
            return;
        q.add(root);
        preorder(root.left);
        preorder(root.right);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.