def test_strOfMultilevelTree(self): a = trees.Node(data="a") b = trees.Node(data="b") c = trees.Node(left=a, right=b, data="c") e = trees.Node(data="e") d = trees.Node(left=c, right=e, data="d") self.assertEqual(str(d), "(d: (c: a b) e)")
def test_onNodeTraversalOrder(self): d = trees.Node(data="d", right=trees.Node(data="e"), left=trees.Node(data="c", right=trees.Node(data="b"), left=trees.Node(data="a"))) path = [] def recordPath(node): path.append(node.data) trees.BFS(d, onNode=recordPath) self.assertEqual(path, ["d", "c", "e", "a", "b"])
def input_tree(): a = trees.Node(50) b = a.addleft(48) i = a.addright(52) c = b.addleft(25) d = c.addleft(10) f = c.addright(30) e = d.addleft(5) g = f.addleft(28) h = f.addright(32) j = i.addleft(51) k = i.addright(54) return a, b,i
if node1 == None and node2 == None: return True if (node1 == None and node2 != None) or (node2 == None and node1 != None): return False if node1.data == node2.data: return same_tree(node1.left, node2.left) and same_tree( node1.right, node2.right) else: return False def check_subtree(root1, root2): if same_tree(root1, root2): return True if not root1: return False return check_subtree(root1.left, root2) or check_subtree( root1.right, root2) n1 = trees.Node(10) a = n1.addleft(5) b = n1.addright(8) a.addleft(1) b.addleft(2) n2 = trees.Node(8) n2.addleft(3) print check_subtree(n1, n2)
def test_strOfOneNodeTree(self): root = trees.Node(data="data") self.assertEqual(str(root), "data")
def test_strOfThreeNodeTree(self): a = trees.Node(data="a") b = trees.Node(data="b") c = trees.Node(left=a, right=b, data="c") self.assertEqual(str(c), "(c: a b)")
#!/usr/bin/python import trees import random a = trees.Node(50) b = a.addleft(48) i = a.addright(52) c = b.addleft(25) d = c.addleft(10) f = c.addright(30) e = d.addleft(5) g = f.addleft(28) h = f.addright(32) j = i.addleft(51) k = i.addright(54) def get_random_node(a): """ Get random nodes """ if not a.left: lc = 0 else: lc = a.left.size index = random.randint(1, a.size)
if node.left: return leftmost(node.left) else: return node def parent_until_greator(node, val): if not node: return None if node.data > val: return node else: return parent_until_greator(node.parent, val) print a = trees.Node(50) b = a.addleft(48) i = a.addright(52) c = b.addleft(25) d = c.addleft(10) f = c.addright(30) e = d.addleft(5) g = f.addleft(28) h = f.addright(32) j = i.addleft(51)
b = [['yes', 'yes', 'maybe'], ['yes', 'yes', 'maybe'], ['no', 'no', 'yes'], ['no', 'yes', 'no'], ['no', 'yes', 'no']] '''tree=tr.DecisionTree() node0=tr.Node(a) child1=tr.splitNode(node0.getNode(), 0, 1) print(child1) child3=tr.Node(child1) node0.getNodeChild().append(child3) child2=tr.splitNode(node0.getNode(), 0, 0) child4=tr.Node(child2) node0.getNodeChild().append(child4) ''' tree = tr.DecisionTree() node0 = tr.Node(a) tree.buildTree(node0) print(node0.getNode()) ''' test=['no','yes',''] res=tr.predict(test, node0) print(res) '''