Simple Java solution using LinkedList


  • 1
    J
    public class Solution {
        public void flatten(TreeNode root) {
            if(root==null)return;
            LinkedList<TreeNode> Que=new LinkedList<TreeNode>();
            TreeNode ptr=root;
            if(root.left!=null)Que.add(root.left);
            if(root.right!=null)Que.add(root.right);
            while(!Que.isEmpty()){
               TreeNode cur=Que.poll();
               if(cur.right!=null)Que.addFirst(cur.right);
               if(cur.left!=null)Que.addFirst(cur.left);
               ptr.right=cur;
               ptr.left=null;
               ptr=cur;
            }
        }
    }

Log in to reply
 

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