Mercurial > louis > peeves
view graphs_trees/link_tree_levels/solution.py @ 0:20fea762903e
Import some exercises and solutions
author | Louis Opter <kalessin@kalessin.fr> |
---|---|
date | Sat, 29 Jun 2013 19:30:31 -0700 |
parents | |
children |
line wrap: on
line source
# NOTE: this is just a dump of my phone screen. 1 -> NULL 2 -> 4 -> NULL 5 -> 6 -> 7 -> 8 -> NULL 9 -> 10 -> 11 -> NULL class Node: left = None right = None sibling = None # Fail… def link_right_sibling(root): stack = [] it = root while it: if stack: it.sibling = stack[-1] if it.right: stack.append(it.right) if it.left: it = it.left elif stack: it = stack.pop() else: break # Fail… def link_right_sibling(root, right=None): if not root: return root.sibling = right link_right_sibling(root.left, root.right) link_right_sibling(root.right) def link_right_sibling(root): if not root: return li = [root, None] it = li.pop(0) while it: if li: it.sibling = li[0] if it.left: li.append(it.left) if it.right: li.append(it.right) if not li: break it = li.pop(0) if it is None: li.append(None) it = li.pop(0)