My Java solution - 0ms


  • 0
    C
    public TreeNode invertTree(TreeNode root) {
    	if (root == null) {
    		return null;
    	}
    	Queue<TreeNode> q = new LinkedList<>();
            q.add(root);
            while(!q.isEmpty()) {
                for (int i = 0; i < q.size(); i++) {
                    TreeNode cur = q.poll();
                    TreeNode temp = cur.right;
                    cur.right = cur.left;
                    cur.left = temp;
                   
                    if (cur.left != null) {
                        q.add(cur.left);
                    }
                    if (cur.right != null) {
                        q.add(cur.right);
                    }
                }
            }
            return root;
        }

Log in to reply
 

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