Concise Java Recursive Solution


  • 2
    Z
     public TreeNode invertTree(TreeNode root) {
        if (root !=null) {
          TreeNode tmp= invertTree(root.left);
          root.left=invertTree(root.right);
          root.right=tmp;
        }
        return root;
      }

  • 0
    C

    Corresponding C++ recursive solution:

    class Solution {
    public:
        TreeNode* invertTree(TreeNode* root) {
            if (root == NULL) {
                return NULL;
            }
            else {
                swap(root->right, root->left);
                invertTree(root->left);
                invertTree(root->right);
                return root;
            }
        }
    };

  • 2
    S

    Your code is very concise,but change the original data, a more functional answer will be:

        public TreeNode invertTree(TreeNode root) {
          if (root  ==  null) return root;
          else {
          TreeNode tmp= new TreeNode(root.val);
          tmp.left = invertTree(root.right);
          tmp.right = invertTree(root.left);
          return tmp;
          }
     }

Log in to reply
 

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