public class Solution { public void Flatten(TreeNode? root) { if (root == null) return; var head = root; var stack = new Stack(); if (root.right != null) stack.Push(root.right); if (root.left != null) stack.Push(root.left); while (stack.Count > 0) { var node = stack.Pop(); head.left = null; head.right = node; head = node; if (node.right != null) stack.Push(node.right); if (node.left != null) stack.Push(node.left); } } }