a few days ago encountered a face test, the study is also a tree, and the normal tree traversal, slightly changed a bit, is to have established a good tree, each connection brother node.
The nodes are defined as follows:
public ilist<node> children;
public Node right;
public string Val;
Contains the child node collection, right node.
Problem: The tree is now set up, but right is empty, connecting all the sibling nodes (not the same parent).
Tree:
After the connection becomes:
Ideas:
1. Traverse each child node and connect the next 1 child nodes of the current child node (except the last one)
2. When traversing each child node, connect the last child node of the current child node to the first child node of the next 1 child nodes (if present)
3. Recursive execution
The implementation is as follows:
void Main () {//setup var root = new Node ("R"); var childGroup1 = new list<node> (); root. Children.add (New node ("A1", new List<node> () {new node ("B1"), new node ("B2")}), Root. Children.add (New node ("A2", new List<node> () {new node ("B3"), new node ("B4")});//Search and link the brother Nodest Ravelandlink (root); Console.WriteLine (root);} static void Travelandlink (Node current) {if (current = = NULL | | current. Children = = null) {return;} var len = current. Children.count;for (var i = 0;i < Len; i++) {//link right if with if (I < len-1) {current. Children[i]. right = current. children[i+1];//Link current son's last son to his next brother's first son if Possibleif (current. Children[i]. Children.any () && current. CHILDREN[I+1]. Children.any ()) {var C1 = current. Children[i]. Children.last (); var C2 = current. CHILDREN[I+1]. Children.first (); C1. right = C2;}} Recursivetravelandlink (current. Children[i]);} Link my last child to Brother's first child if Impossible}public class Node{publicNode (String v, ienumerable<node> children = null) {Val = v; Children = new list<node> (); if (children! = null) {children = children. ToArray ();} right = null;} public ilist<node> children; Public Node right;public string Val; }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Algorithm surface question--all sibling nodes of the connection tree