//---------------------------------------------------------------------------------------------------- // O(1) space method: change structure of node with next link in both directions public static List<int> Traverse(PowerTreeNode root) { if (root == null) return new List<int>(); LinkNextRight(root); LinkNextLeft(root); List<int> res = new List<int>(); // true for dirction from right to left, false for direction from left to right bool leftDir = true; PowerTreeNode curr = root; PowerTreeNode head = root.left != null ? root.left : root.right; bool gotHead = false; // flag for finding head node in next level while (head != null) { while (curr != null) { res.Add(curr.val); if (leftDir) { PowerTreeNode temp = curr.left != null ? curr.left : curr.right; if (temp != null) { head = temp; gotHead = true; } curr = curr.leftNext; } else { PowerTreeNode temp = curr.right != null ? curr.right : curr.left; if (temp != null) { head = temp; gotHead = true; } curr = curr.rightNext; } if (!gotHead) head = null; } leftDir = !leftDir; curr = head; gotHead = false; } return res; }
// link nodes in same level in <- direction private static void LinkNextLeft(PowerTreeNode root) { if (root == null) return; PowerTreeNode curr = root; // head node in next level PowerTreeNode head = root.right != null ? root.right : root.left; PowerTreeNode prev = null; // previous node in next level // when next level exists while (head != null) { // walk through current level and link nodes in next level while (curr != null) { if (prev == null) { head = curr.right != null ? curr.right : curr.left; prev = head; } if (curr.right != null && curr.right != prev) { prev.leftNext = curr.right; prev = curr.right; } if (curr.left != null && curr.left != prev) { prev.leftNext = curr.left; prev = curr.left; } curr = curr.leftNext; } // move to next level curr = head; prev = null; } }