class Tree(object): def __str__ (self): if self.right is None: r= "" else: r=str(self.right) if self.left is None: l= "" else: l=str(self.left) return "("+l+" "+self.id+" "+r+")" def __init__(self,id,right=None,left=None): self.right = right self.left = left self.id = id def __add__(self,other): return Tree("",self,other) def __getitem__(self,id): if id=="L": return self.left elif id=="R": return self.right else: raise ValueError('Invalid index:'+str(id)) def __setitem__(self,id,value): if id=="L": self.left = value elif id=="R": self.right = value else: raise ValueError('Invalid index:'+str(id)) try: root =Tree("R",Tree("2",Tree("3")),Tree("1",None,Tree("4",Tree("5")))) def rev(t) : if t is None: return None else: return Tree(t.id,rev(t.left),rev(t.right)) print(root) print(rev(root)) s = root+rev(root) s.id = "S" s["T"]="DUDU" s["R"]="BUBU" print(s) except IOError as ioe: print("ERROR") except ValueError as ve: print("Value error:"+str(ve)) except : print("ERROR")
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question