Share my solution in Java


  • 0
    Y
    public class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root == null || (root.left == null && root.right == null)){
                return root;
            }
            return invertNode(root);
        }
        public TreeNode invertNode(TreeNode node){
            if(node == null){
                return node;
            }
            
            TreeNode tmpNode = invertNode(node.left);
            node.left = invertNode(node.right);
            node.right = tmpNode;
            return node;
        }
    }

  • 0
    Y
    // inv(a, b) -> swap(inv(a.left, a.right), inv(b.left, b.right))
    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;
        }
    }

  • 0
    J

    Here is my shortest solution :

    public class Solution {
        public TreeNode invertTree(TreeNode root) {
            if (null != root && (null != root.left || null != root.right)) {
                TreeNode tmpNode = root.left;
                root.left = invertTree(root.right);
                root.right = invertTree(tmpNode);
            }
            return root;
        }
    }

Log in to reply
 

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