114. Flatten Binary Tree to Linked List

This commit is contained in:
2026-03-25 23:18:30 +03:00
parent a8727e17a1
commit 6b483ea6d1
5 changed files with 131 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
public class Solution
{
public void Flatten(TreeNode? root)
{
if (root == null)
return;
var head = root;
var stack = new Stack<TreeNode>();
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);
}
}
}