Skip to content

Instantly share code, notes, and snippets.

@mrjohannchang
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrjohannchang/4a6dca23dd1fdb455371 to your computer and use it in GitHub Desktop.
Save mrjohannchang/4a6dca23dd1fdb455371 to your computer and use it in GitHub Desktop.
class Solution:
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self, root):
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
@Wendly
Copy link

Wendly commented Jun 12, 2015

public class Solution {
    public TreeNode invertTree(TreeNode root) {
        LinkedList<TreeNode> tasks = new LinkedList<TreeNode>();
        tasks.add(root);
        while (tasks.size() > 0) {
            TreeNode node = tasks.removeFirst();

            if (node == null) continue;

            TreeNode tmp = node.right;
            node.right = node.left;
            node.left = tmp;

            tasks.add(node.left);
            tasks.add(node.right);
        }
        return root;
    }
}

@mrjohannchang
Copy link
Author

class Solution:
    # @param {TreeNode} root
    # @return {TreeNode}
    def invertTree(self, root):
        q = [root]
        while q:
            node = q.pop(0)
            if node:
                node.left, node.right = node.right, node.left
                q.extend([node.left, node.right])
        return root

@qazq
Copy link

qazq commented Jun 12, 2015

public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;

        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;

        invertTree(root.left);
        invertTree(root.right);

        return root;
    }
}

@yongjhih
Copy link

public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return root;
        return swap(invertTree(root.left), invertTree(root.right), root);
    }

    TreeNode swap(TreeNode left, TreeNode right, TreeNode root) {
        root.left = right;
        root.right = left;
        return root;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment