<s> import sys <EOL> import weakref <EOL> from collections import deque <EOL> from pydispatch import dispatcher <EOL> class TreeNode ( object ) : <EOL> """<STR_LIT>""" <EOL> on_parent_changed = "<STR_LIT>" <EOL> on_child_added = "<STR_LIT>" <EOL> on_child_removed = "<STR_LIT>" <EOL> def __init__ ( self ) : <EOL> """<STR_LIT>""" <EOL> super ( TreeNode , self ) . __init__ ( ) <EOL> self . _parent = None <EOL> self . _children = set ( ) <EOL> def add_child ( self , node ) : <EOL> """<STR_LIT>""" <EOL> if node . parent != None : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> self . _children . add ( node ) <EOL> node . parent = self <EOL> dispatcher . send ( TreeNode . on_child_added , self , node ) <EOL> def remove_child ( self , node ) : <EOL> """<STR_LIT>""" <EOL> self . _children . remove ( node ) <EOL> node . parent = None <EOL> dispatcher . send ( TreeNode . on_child_removed , self , node ) <EOL> @ property <EOL> def children ( self ) : <EOL> return self . _children <EOL> @ property <EOL> def parent ( self ) : <EOL> """<STR_LIT>""" <EOL> if self . _parent != None : <EOL> return self . _parent ( ) <EOL> return None <EOL> @ parent . setter <EOL> def parent ( self , parent ) : <EOL> """<STR_LIT>""" <EOL> if parent == self . parent : <EOL> return <EOL> new_parent = None <EOL> if parent : <EOL> new_parent = weakref . ref ( parent ) <EOL> if self . parent : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> if self not in parent . children : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> old_parent = self . parent <EOL> self . _parent = new_parent <EOL> dispatcher . send ( TreeNode . on_parent_changed , self , old_parent , parent ) <EOL> def dfs ( self ) : <EOL> queue = deque ( [ self ] ) <EOL> while queue : <EOL> node = queue . pop ( ) <EOL> if hasattr ( node , '<STR_LIT>' ) : <EOL> queue . extend ( list ( node . _children ) ) <EOL> yield node <EOL> def bfs ( self ) : <EOL> queue = deque ( [ self ] ) <EOL> while queue : <EOL> node = queue . pop ( ) <EOL> if hasattr ( node , '<STR_LIT>' ) : <EOL> queue . extendleft ( list ( node . _children ) ) <EOL> yield node <EOL> def predecessors ( self ) : <EOL> parent = self . parent <EOL> while parent != None : <EOL> yield parent <EOL> parent = parent . parent </s>
