public static void NextSiblingBinaryTree(BTNextSiblingNode root) { Queue <BTNextSiblingNode> btNodeQueue = new Queue <BTNextSiblingNode>(); if (root != null) { btNodeQueue.Enqueue(root); btNodeQueue.Enqueue(null); while (btNodeQueue.Count > 0) { var temp = btNodeQueue.Dequeue(); if (temp == null) { if (btNodeQueue.Count != 0) { btNodeQueue.Enqueue(null); } } else { temp.NextSibling = btNodeQueue.Peek(); if (temp.LChild != null) { btNodeQueue.Enqueue(temp.LChild); } if (temp.RChild != null) { btNodeQueue.Enqueue(temp.RChild); } } } } }
public static void NextSiblingBinartyTreeRecursive(BTNextSiblingNode root) { if (root == null) { return; } if (root.LChild != null) { root.LChild.NextSibling = root.RChild; } if (root.RChild != null) { root.RChild.NextSibling = root.NextSibling != null ? root.NextSibling.LChild : null; } NextSiblingBinartyTreeRecursive(root.LChild); NextSiblingBinartyTreeRecursive(root.RChild); }