public Node1(int _val, Node1 _left, Node1 _right, Node1 _next) { val = _val; left = _left; right = _right; next = _next; }
public Node1 Connect(Node1 root) { if (root == null) { return(root); } var nodes = new Queue <Node1>(); nodes.Enqueue(root); var levelNodes = new List <Node1>(); while (nodes.Count != 0) { var size = nodes.Count; levelNodes = new List <Node1>(); for (var i = 0; i < size; i++) { var node = nodes.Dequeue(); if (node.left != null) { nodes.Enqueue(node.left); } if (node.right != null) { nodes.Enqueue(node.right); } levelNodes.Add(node); if (levelNodes.Count >= 1 && i >= 1) { levelNodes[i - 1].next = levelNodes[i]; } } } return(root); }