Accepted Java solution (postorder)


  • 0
    public TreeNode invertTree(TreeNode root) {
      if (root == null)
        return null;
      
      // postorder traversal
      invertTree(root.left);
      invertTree(root.right);
      
      // swap left and right nodes
      TreeNode left = root.left;
      
      root.left = root.right;
      root.right = left;
      
      return root;
    }

  • 0

    0 ms solution

    struct TreeNode* invertTree(struct TreeNode* root) {
            if (!root )
        {
            return NULL;
        }
        if (!root->left  &&
            !root->right )
        {
            return root;
        }
        
        struct TreeNode* tmp;
        tmp = root->left;
        root->left = root->right;
        root->right = tmp;
        invertTree(root->left);
        invertTree(root->right);
        
        return root;
    

    }


  • 0
    F

    Is it a Java solution?


Log in to reply
 

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