Really straight-forward C# solution faster than 78%

  • 0

    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>();
                while (pending.Count > 0)
                    current = pending.Pop();
                    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.