Recursive C# solution


  • 1
    E
    public class Solution {
        public TreeNode InvertTree(TreeNode root) {
            Invert(root);
            
            return root;
        }
        
        public void Invert(TreeNode root)
        {
            if (root == null) 
                return;
            
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
            
            Invert(root.left);
            Invert(root.right);
        }
    }
    

    Basic idea is that you need to invert pointers pointing to root's left and right children at any time going down from the root.
    Therefore I'm keeping a temporary variable (temp) for left child, assigning right to left and then temp to right. This is a simple swap operation if you will.
    Above is the core of the algorithm. We need to apply this core to both left and right children recursively noting that base case being (root == null) return;.


Log in to reply
 

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