C++ & Java simple solutions


  • -2
    O

    C++:

    class Solution {
    public:
        TreeNode* invertTree(TreeNode* root) {
            change(root);
            return root;
        }
        void change(TreeNode* focusNode)
        
            
        {
            if(!focusNode ||(!focusNode->right &&!focusNode->left))return;
            else if(!focusNode->right)
            {
                focusNode->right=focusNode->left;
                focusNode->left=NULL;
                change(focusNode->left);
                change(focusNode->right);
            }
            else if(!focusNode->left)
            {
                focusNode->left=focusNode->right;
                focusNode->right=NULL;
                change(focusNode->left);
                change(focusNode->right);
            }
            else {
                TreeNode* temp=focusNode->right;
                focusNode->right=focusNode->left;
                focusNode->left=temp;
                change(focusNode->left);
                change(focusNode->right);
            }
            
        }
        
    };
    

    JAVA :

    public class Solution {
        
        public TreeNode invertTree(TreeNode root) {
            change(root);
            return root;
        }
        
        public void change(TreeNode focusNode)
        {
            if(focusNode==null ||(focusNode.right==null &&focusNode.left==null))return;
            else if(focusNode.right==null)
            {
                focusNode.right=focusNode.left;
                focusNode.left=null;
                change(focusNode.left);
                change(focusNode.right);
            }
            else if(focusNode.left==null)
            {
                focusNode.left=focusNode.right;
                focusNode.right=null;
                change(focusNode.left);
                change(focusNode.right);
            }
            else {
                TreeNode temp=focusNode.right;
                focusNode.right=focusNode.left;
                focusNode.left=temp;
                change(focusNode.left);
                change(focusNode.right);
            }
            
        }
    }

Log in to reply
 

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