Really straight-forward C# solution faster than 78%


  • 0
    E

    Iterative in-order traversal swapping every node. Not sure why it is more performant than other solutions, except all the C# solutions I saw were recursive.

    public class Solution {
        public static void Swap(TreeNode root)
        {
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
        }
    
        public TreeNode InvertTree(TreeNode root) {
            if (root != null)
            {
                TreeNode current;
                var pending = new Stack<TreeNode>();
                pending.Push(root);
                while (pending.Count > 0)
                {
                    current = pending.Pop();
                    Swap(current);
                    if (current.left != null) pending.Push(current.left);
                    if (current.right != null) pending.Push(current.right);
                }
            }
            return root;
        }
    }

Log in to reply
 

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