114. Flatten Binary Tree to Linked List
This commit is contained in:
27
114. Flatten Binary Tree to Linked List/Solution.cs
Normal file
27
114. Flatten Binary Tree to Linked List/Solution.cs
Normal 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);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user