binary tree python
class Binarytree:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def addChild(self, data):
if data == self.data:
return
if data < self.data:
if self.left:
self.left.addChild(data)
else:
self.left = Binarytree(data)
else:
if self.right:
self.right.addChild(data)
else:
self.right = Binarytree(data)
def inorder(self):
element = [ ]
if self.left:
element += self.left.inorder()
element.append(self.data)
if self.right:
element += self.right.inorder()
return element
def search(self,val):
if val == self.data:
return True
if val < self.data:
if self.left:
return self.left.search(val)
else:
return False
else:
if self.right:
return self.right.search(val)
else:
return False
def buildtree(element):
root = Binarytree(element[0])
for i in range(1,len(element)):
root.addChild(element[i])
return root
if __name__ == '__main__':
element = [39, 87, 21, 42, 95, 52, 12]
tree = buildtree(element)
print(tree.inorder())
print(tree.search(38))
0
0
// Binary Tree in Golang
package main
import (
"fmt"
"os"
"io"
)
type BinaryNode struct {
left *BinaryNode
right *BinaryNode
data int64
}
type BinaryTree struct {
root *BinaryNode
}
func (t *BinaryTree) insert(data int64) *BinaryTree {
if t.root == nil {
t.root = &BinaryNode{data: data, left: nil, right: nil}
} else {
t.root.insert(data)
}
return t
}
func (n *BinaryNode) insert(data int64) {
if n == nil {
return
} else if data <= n.data {
if n.left == nil {
n.left = &BinaryNode{data: data, left: nil, right: nil}
} else {
n.left.insert(data)
}
} else {
if n.right == nil {
n.right = &BinaryNode{data: data, left: nil, right: nil}
} else {
n.right.insert(data)
}
}
}
func print(w io.Writer, node *BinaryNode, ns int, ch rune) {
if node == nil {
return
}
for i := 0; i < ns; i++ {
fmt.Fprint(w, " ")
}
fmt.Fprintf(w, "%c:%v\n", ch, node.data)
print(w, node.left, ns+2, 'L')
print(w, node.right, ns+2, 'R')
}
func main() {
tree := &BinaryTree{}
tree.insert(100).
insert(-20).
insert(-50).
insert(-15).
insert(-60).
insert(50).
insert(60).
insert(55).
insert(85).
insert(15).
insert(5).
insert(-10)
print(os.Stdout, tree.root, 0, 'M')
}
Thank you!
0
0
4.14
7
Binary Tree implementation at this link:
https://github.com/shreyasvedpathak/Data-Structure-Python/tree/master/BinaryTrees
Thank you!
7
0
0
0
Binary Tree implementation at this link:
https://github.com/shreyasvedpathak/Data-Structure-Python/tree/master/BinaryTrees
Thank you!
0
0
3.5
8
# Create Decision Tree classifer object
clf = DecisionTreeClassifier(criterion="entropy", max_depth=3)
# Train Decision Tree Classifer
clf = clf.fit(X_train,y_train)
#Predict the response for test dataset
y_pred = clf.predict(X_test)
# Model Accuracy, how often is the classifier correct?
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
Thank you!
8
0
0
5
Binary Search Tree at this link:
https://github.com/shreyasvedpathak/Data-Structure-Python/tree/master/BinaryTrees
Thank you!
5
0
Are there any code examples left?
New code examples in category Python