Last active
August 29, 2015 14:03
-
-
Save akiniwa/157975669cec8d023069 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
class Tree: | |
def __init__(self, value=0): | |
self.value = value | |
self.child = [] | |
def insertChild(self, index, v): | |
self.child.insert(index, Tree(v)) | |
def getChild(self, index): | |
return self.child[index] | |
def getAllChild(self): | |
return self.child | |
def getValue(self): | |
return self.value | |
def getChildSize(self): | |
return len(self.child) | |
class BinaryTree: | |
def __init__(self,rootObj): | |
self.key = rootObj | |
self.leftChild = None | |
self.rightChild = None | |
def insertLeft(self,newNode): | |
# ノードの存在で分岐が必要 | |
if self.leftChild == None: | |
# 存在しなければ、そのまま追加 | |
self.leftChild = BinaryTree(newNode) | |
else: | |
# 存在すれば、新しくノードを作って | |
t = BinaryTree(newNode) | |
# 元々あったやつを、新しいノードにくっつけて | |
t.leftChild = self.leftChild | |
# 元々あったところに、新しいノードを追加 | |
self.leftChild = t | |
def insertRight(self,newNode): | |
if self.rightChild == None: | |
self.rightChild = BinaryTree(newNode) | |
else: | |
t = BinaryTree(newNode) | |
t.rightChild = self.rightChild | |
self.rightChild = t | |
def getRightChild(self): | |
return self.rightChild | |
def getLeftChild(self): | |
return self.leftChild | |
def setRootVal(self,obj): | |
self.key = obj | |
def getRootVal(self): | |
return self.key | |
""" | |
r = BinaryTree(3) | |
print(r.getRootVal()) | |
print(r.getLeftChild()) | |
r.insertLeft(4) | |
print(r.getLeftChild().getRootVal()) | |
r.insertRight(2) | |
print(r.getRightChild().getRootVal()) | |
r.getRightChild().setRootVal('hello') | |
print(r.getRightChild().getRootVal()) | |
""" | |
t = Tree(4) | |
t.insertChild(index=0, v=3) | |
t.insertChild(index=1, v=7) | |
t.insertChild(index=2, v=5) | |
t.getChild(index=0).insertChild(index=0, v=2) | |
t.getChild(index=0).insertChild(index=0, v=2) | |
t.getChild(index=0).insertChild(index=0, v=2) | |
t.getChild(index=1).insertChild(index=0, v=5) | |
t.getChild(index=1).insertChild(index=1, v=6) | |
t.getChild(index=1).insertChild(index=1, v=6) | |
t.getChild(index=1).getChild(0).insertChild(index=0, v=12) | |
def depthSearch(_t, _v): | |
if _t.getValue()==_v: | |
return _v | |
if _t.getChildSize()==0: | |
print(_t.getValue()), | |
pass | |
#return _t.getValue() | |
else: | |
print _t.getValue() | |
for i in range(_t.getChildSize()): | |
depthSearch(_t.getChild(i), _v) | |
else: | |
print "" | |
depthSearch(t, 8) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment