Files
Leetcode/114. Flatten Binary Tree to Linked List/Solution.cs

27 lines
651 B
C#

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);
}
}
}