C
C#•3y ago
KidKai25

My head hurts understanding this LINQ

static IEnumerable<string> serializeToEnumerable(TreeNode root)
=> root is null
? new string[] { String.Empty }
: serializeToEnumerable(root.left)
.Concat(serializeToEnumerable(root.right))
.Prepend(root.val.ToString());
static IEnumerable<string> serializeToEnumerable(TreeNode root)
=> root is null
? new string[] { String.Empty }
: serializeToEnumerable(root.left)
.Concat(serializeToEnumerable(root.right))
.Prepend(root.val.ToString());
18 Replies
KidKai25
KidKai25OP•3y ago
I thought I knew Linq
Saber
Saber•3y ago
not really much linq happening here. what is confusing
KidKai25
KidKai25OP•3y ago
I mean I never saw recursion + Concat + Prepend this way really cool catpog I couldn't come up with this?
Saber
Saber•3y ago
i don't know. might not have a good enough understanding of how to solve a problem and the overall knowledge of how things can play together
KidKai25
KidKai25OP•3y ago
thank you. You are awesome as always.
TheBoxyBear
TheBoxyBear•3y ago
Converting a TreeNode to a set of strings. ?: is a ternary expression a ? b : c returning either b or c depending on the value of bool a If left and right have two way references, this might cause a stakcoverflow however
KidKai25
KidKai25OP•3y ago
my one issue in understanding was the calling of recursive methods like again inside Concat
TheBoxyBear
TheBoxyBear•3y ago
Considering nodes A B and C from left to right
KidKai25
KidKai25OP•3y ago
Need to wrap my head around more.
TheBoxyBear
TheBoxyBear•3y ago
Resurcion to serialize all the nodes to the left and right Not just the one node
KidKai25
KidKai25OP•3y ago
it's a binary tree though
TheBoxyBear
TheBoxyBear•3y ago
Though I'm worried it might loop endlessly. Say if you were to serialize node B, it starts by serializing A but by serializing A, it also serializes B as part of .Concat(serializeToEnumerable(root.right)) Then it's fine So left and right are the branches from the node, right?
KidKai25
KidKai25OP•3y ago
yup
TheBoxyBear
TheBoxyBear•3y ago
Trees and recursion go hand in hand Continuing to navigate a tree from a node is the same as navigating a full tree with the same node as root
KidKai25
KidKai25OP•3y ago
yes right
TheBoxyBear
TheBoxyBear•3y ago
So the result for a node is [This, Left, Right]
KidKai25
KidKai25OP•3y ago
yes and this is called PreOrder way I get it now, thank you BoxyBear and Saber 🙂
TheBoxyBear
TheBoxyBear•3y ago
np
Want results from more Discord servers?
Add your server