def sortedarraytoBSTrecu(self, nums, begin, end): if begin > end: return None mid = begin + (end - begin) // 2 root = TN(nums[mid]) root.left = self.sortedarraytoBSTrecu(nums, begin, mid - 1) root.right = self.sortedarraytoBSTrecu(nums, mid + 1, end) return root
"""解法1:递归法 - 时间复杂度:O(MN)。其中 M,N 分别为树 A 和树 B 的节点数量。 - 空间复杂度:O(M)。 """ class Solution: def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool: def recur(A, B): if not B: return True if not A or A.val != B.val: return False return recur(A.left, B.left) and recur(A.right, B.right) return bool(A and B) and (recur(A, B) or self.isSubStructure( A.left, B) or self.isSubStructure(A.right, B)) if __name__ == "__main__": A = TreeNode(3) A.left = TreeNode(4) A.right = TreeNode(5) A.left.left = TreeNode(1) A.left.right = TreeNode(2) B = TreeNode(4) B.left = TreeNode(1) print(A, B) print(Solution().isSubStructure(A, B))
def flatten(node): if node is None: return None if node.left is None and node.right is None: return node left = flatten(node.left) right = flatten(node.right) if left: left.right = node.right node.right = node.left node.left = None return right if right is not None else left if __name__ == "__main__": tree = Node(1) tree.left = Node(2) tree.left.left = Node(3) tree.left.right = Node(4) tree.right = Node(5) tree.right.right = Node(6) print(tree) flatten(tree) node = tree while node: print(node.val) node = node.right
from binarytree import Node as TN class Solution(object): def invertbinaryTree(self, root): if root is not None: root.left, root.right = \ self.invertbinaryTree(root.right), self.invertbinaryTree(root.left) return root S = Solution() root = TN(4) root.left = TN(2) root.left = TN(2) root.right = TN(7) root.left.left = TN(1) root.left.right = TN(3) root.right.left = TN(6) root.right.right = TN(9) print root print S.invertbinaryTree(root)
def test_node_set_attributes(): root = Node(1) assert root.left is None assert root.right is None assert root.value == 1 assert repr(root) == 'Node(1)' left_child = Node(2) root.left = left_child assert root.left is left_child assert root.right is None assert root.value == 1 assert root.left.left is None assert root.left.right is None assert root.left.value == 2 assert repr(left_child) == 'Node(2)' right_child = Node(3) root.right = right_child assert root.left is left_child assert root.right is right_child assert root.value == 1 assert root.right.left is None assert root.right.right is None assert root.right.value == 3 assert repr(right_child) == 'Node(3)' last_node = Node(4) left_child.right = last_node assert root.left.right is last_node assert root.left.right.value == 4 assert repr(last_node) == 'Node(4)' with pytest.raises(NodeValueError) as err: # noinspection PyTypeChecker Node('this_is_not_an_integer') assert str(err.value) == 'node value must be a number' with pytest.raises(NodeTypeError) as err: # noinspection PyTypeChecker Node(1, 'this_is_not_a_node') assert str(err.value) == 'left child must be a Node instance' with pytest.raises(NodeTypeError) as err: # noinspection PyTypeChecker Node(1, Node(1), 'this_is_not_a_node') assert str(err.value) == 'right child must be a Node instance' with pytest.raises(NodeValueError) as err: root.value = 'this_is_not_an_integer' assert root.value == 1 assert str(err.value) == 'node value must be a number' with pytest.raises(NodeTypeError) as err: root.left = 'this_is_not_a_node' assert root.left is left_child assert str(err.value) == 'left child must be a Node instance' with pytest.raises(NodeTypeError) as err: root.right = 'this_is_not_a_node' assert root.right is right_child assert str(err.value) == 'right child must be a Node instance'
right = all_sequences(root.right) or [[]] # At a minimum, left and right must be a list containing an empty list # for the following nested loop for i in range(len(left)): for j in range(len(right)): weaved = [] weave_lists(left[i], right[j], weaved, prefix) answer.extend(weaved) return answer if __name__ == "__main__": t = Node(4) t.right = Node(6) node1 = Node(1) t.left = node1 node1.left = Node(0) node1.right = Node(3) # solution = all_sequences(t) # for e, item in enumerate(solution): # print(f"{e:03}: {item}") first = [1] second = [2, 3] result = [] prefix = [4]
return s == 0 else: ans = 0 # Otherwise check both subtrees subSum = s - root.value # If we reach a leaf node and sum becomes 0, then # return True if (subSum == 0 and root.left == None and root.right == None): return True if root.left is not None: ans = ans or self.roottoleafpathSum(root.left, subSum) if root.right is not None: ans = ans or self.roottoleafpathSum(root.right, subSum) return ans S = Solution() s = 21 root = TN(10) root.left = TN(8) root.right = TN(2) root.left.right = TN(5) root.left.left = TN(3) root.right.left = TN(2) print(root) print S.roottoleafpathSum(root, s)
"""解法2:层次遍历+倒序 - 时间复杂度:O(N) - 空间复杂度:O(N) """ class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] res, queue = [], collections.deque() queue.append(root) while queue: tmp = [] for _ in range(len(queue)): node = queue.popleft() tmp.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.append(tmp[::-1] if len(res) % 2 else tmp) return res if __name__ == "__main__": root = TreeNode(3) root.left = TreeNode(9) root.right = TreeNode(20) root.right.left = TreeNode(15) root.right.right = TreeNode(7) print(root) print(Solution().levelOrder(root))
#!/usr/bin/python3 from binarytree import Node root = Node(3) root.left = Node(6) root.right = Node(8) # Getting binary tree print('Binary tree :', root) # Getting list of nodes print('List of nodes :', list(root)) # Getting inorder of nodes print('Inorder of nodes :', root.inorder) # Checking tree properties print('Size of tree :', root.size) print('Height of tree :', root.height) # Get all properties at once print('Properties of tree : \n', root.properties) # Python program to introduce Binary Tree # A class that represents an individual node in a # Binary Tree class Node: def __init__(self,key):
# -*- coding: utf-8 -*- """ Created on Mon Jan 20 17:52:10 2020 @author: wyue Pypi Documentation: https://pypi.org/project/binarytree/ """ from binarytree import Node r1 = Node(1) r2 = Node(2) r1.left = Node(3) r1.right = Node(4) r2.left = Node(5) r2.right = Node(6) root = Node(0) root.left = r1 root.right = r2 print(r1) print(r2) print(root) print("Max leaf depth", root.max_leaf_depth) print("Min leaf depth", root.min_leaf_depth)
import sys from binarytree import Node as TN class Solution(object): def isBST(self, root): return self.isBSTRecu(root, -sys.maxint, sys.maxint) def isBSTRecu(self, root, mini, maxi): if root is None: return True return mini < root.value and root.value < maxi and \ self.isBSTRecu(root.left, mini, root.value) and \ self.isBSTRecu(root.right, root.value, maxi) S = Solution() root = TN(1) root.left = TN(2) root.right = TN(3) print root.preorder print root.inorder print root.postorder print(root) print S.isBST(root)
from binarytree import tree, bst, Node a = tree(height=3, is_perfect=False) b = bst(height=3, is_perfect=True) c = Node(5) c.left = Node(3) c.right = Node(10) c.left.left = Node(2) c.left.right = Node(4) c.right.left = Node(9) c.right.right = Node(15) #print(a) #print(b) #print(c) bt = bst(height=5, is_perfect=True) print(bt) num = int(input('Что найти: ')) def search(bin_tree, number, path=''): if bin_tree.value == number: return f'Число {number} обнаружено по следующему пути: \nКорень{path}' if number < bin_tree.value and bin_tree.left != None: return search(bin_tree.left, number, path=f'{path}\nШаг влево') if number > bin_tree.value and bin_tree.right != None: return search(bin_tree.right, number, path=f'{path}\nШаг вправо') return f'Число {number} отсутствует'
self.value = value self.left = left self.right = right #дерево из модуля a = tree(height=3, is_perfect=True) print(a) # binary дерево из модуля b = bst(height=3, is_perfect=True) print(b) #manual tree root = Node(8) root.left = Node(5) root.right = Node(25) root.left.right = Node(7) root.right.right = Node(100) print(root) # Функция поиска числа и вывода пути. print('*' * 50) bt = bst(height=5, is_perfect=False) print(bt) num = int(input('Число для поиска: ')) # Функция рекурсивного поиска def search(bin_tree, number, path=''): if bin_tree.value == number: return f'Число {number} обнаружено по следующему пути:\nКорень{path}'
if tree_1 is not None and tree_2 is not None: return ((tree_1.value == tree_2.value) and self.identical_trees(tree_1.left, tree_2.left) and self.identical_trees(tree_1.right, tree_2.right)) return False def isSubtree(self, s, t): if not s: return False if self.identical_trees(s, t): return True if self.isSubtree(s.left, t) or self.isSubtree(s.right, t): return True return False S = Solution() root1 = Treenode(30) root1.left = Treenode(20) root1.right = Treenode(40) root1.left.left = Treenode(20) root1.left.right = Treenode(40) print root1 root2 = Treenode(20) root2.left = Treenode(20) root2.right = Treenode(40) print root2 print S.isSubtree(root1, root2)
while len(currentNodes) > 0: if len(currentNodes) > maxWidth: maxWidth = len(currentNodes) nextNodes = [] for node in currentNodes: if node.left is not None: nextNodes.append(node.left) if node.right is not None: nextNodes.append(node.right) currentNodes = nextNodes return {'maxWidth', maxWidth} if __name__ == "__main__": root = Node(2) root.left = Node(4) root.right = Node(5) root.left.left = Node(7) root.left.left.left = Node(13) root.left.right = Node(8) root.left.right.left = Node(12) root.left.right.right = Node(14) root.right.left = Node(16) root.right.left.right = Node(19) root.right.left.left = Node(20) root.right.right = Node(21) print(root) print(levelorder(root))
return t1 if __name__ == '__main__': # 用法 https://github.com/joowani/binarytree # from binarytree import tree # mytree = tree() # print( mytree ) from binarytree import Node # root = Node(1) # root.left = Node(2) # root.right = Node(3) # root.left.right = Node(4) # print( root ) t1 = Node(1) t1.left = Node(3) t1.right = Node(2) t1.left.left = Node(5) t2 = Node(2) t2.left = Node(1) t2.right = Node(3) t2.left.right = Node(4) t2.right.right = Node(7) print(t1), print(t2) print(Solution().mergeTrees(t1, t2))
from binarytree import tree, bst, Node, build class MyNode: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right # неполное дерево высотой 4 листа a = tree(height=4, is_perfect=False) print(a) b = bst(height=3, is_perfect=True) print(b) c = Node(7) c.left = Node(3) c.right = Node(11) c.left.left = Node(1) c.left.right = Node(5) c.right.left = Node(9) c.right.right = Node(13) print(c) d = build([7, 3, 11, 1, 5, 9, 3, None, 2, None, 6]) print(d)
elif tree1 == None or tree2 == None: return False elif tree1.value != tree2.value: return False else: return matchTree(tree1.left, tree2.left) and matchTree( tree1.right, tree2.right) if __name__ == "__main__": node4 = Node(4) node1 = Node(1) node10 = Node(10) node4.left = node1 node4.right = node10 node16 = Node(16) node32 = Node(32) node1.left = node16 node1.right = node32 node41 = Node(41) node76 = Node(76) node10.left = node41 node10.right = node76 bigTree = node4 smallTree = node10
def test_convert(): for invalid_argument in [1, 'foo', int]: with pytest.raises(ValueError) as err: convert(invalid_argument) assert str(err.value) == 'Expecting a list or a node' assert convert(None) == [] # Convert trees to lists for convert_func in [convert, lambda node: node.convert()]: root = Node(1) assert convert_func(root) == [1] root.right = Node(3) assert convert_func(root) == [1, None, 3] root.left = Node(2) assert convert_func(root) == [1, 2, 3] root.left.right = Node(4) assert convert_func(root) == [1, 2, 3, None, 4] root.right.left = Node(5) assert convert_func(root) == [1, 2, 3, None, 4, 5] root.right.right = Node(6) assert convert_func(root) == [1, 2, 3, None, 4, 5, 6] root.right.right = Node(None) with pytest.raises(ValueError) as err: convert_func(root) assert str(err.value) == 'A node cannot have a null value' root.right.right = {} with pytest.raises(ValueError) as err: assert convert_func(root) assert str(err.value) == 'Found an invalid node in the tree' # Convert lists to trees with pytest.raises(ValueError) as err: convert([None, 2, 3]) assert str(err.value) == 'Node missing at index 0' with pytest.raises(ValueError) as err: convert([1, 2, None, 3, 4, 5, 6]) assert str(err.value) == 'Node missing at index 2' assert convert([]) is None bt = convert([1]) assert attr(bt, 'value') == 1 assert attr(bt, 'left') is None assert attr(bt, 'right') is None bt = convert([1, 2]) assert attr(bt, 'value') == 1 assert attr(bt, 'left.value') == 2 assert attr(bt, 'right') is None assert attr(bt, 'left.left') is None assert attr(bt, 'left.right') is None bt = convert([1, None, 3]) assert attr(bt, 'value') == 1 assert attr(bt, 'left') is None assert attr(bt, 'right.value') == 3 assert attr(bt, 'right.left') is None assert attr(bt, 'right.right') is None bt = convert([1, 2, 3]) assert attr(bt, 'value') == 1 assert attr(bt, 'left.value') == 2 assert attr(bt, 'right.value') == 3 assert attr(bt, 'left.left') is None assert attr(bt, 'left.right') is None assert attr(bt, 'right.left') is None assert attr(bt, 'right.right') is None
q: 'TreeNode') -> 'TreeNode': if not root: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if root == p or root == q: return root if not left: return right if not right: return left return root if __name__ == "__main__": # root = [3,5,1,6,2,0,8,null,null,7,4] root = TreeNode(3) root.left = TreeNode(5) root.right = TreeNode(1) root.left.left = TreeNode(6) root.left.right = TreeNode(2) root.right.left = TreeNode(0) root.right.right = TreeNode(8) root.left.right.left = TreeNode(7) root.left.right.right = TreeNode(4) # p = 5 p = root.left # q = 4 q = TreeNode(4) print(root) print(Solution().lowestCommonAncestor(root, p, q)) # 5
for el in text: char_table[el] += 1 char_table = dict(char_table) queue = deque(char_table.items()) while len(queue) > 1: queue = deque(sorted(queue, key=lambda x: x[1])) spam = Node(queue[0][1] + queue[1][1]) if isinstance(queue[0][0], str): spam.left = Node(ord(queue[0][0])) else: spam.left = queue[0][0] if isinstance(queue[1][0], str): spam.right = Node(ord(queue[1][0])) else: spam.right = queue[1][0] queue.popleft() queue[0] = (spam, spam.value) my_tree = queue[0][0] result = None def search(graph, char, in_binary=''): global result if graph.value == ord(char): result = in_binary if graph.left: search(graph.left, char, in_binary=f'{in_binary}0')
def mirror(root): if (root is None): return node = Node(root.value) node.right = mirror(root.left) node.left = mirror(root.right) return node
# So if -1, keep throwing that back up and skip recursive calls l = check_int(root.left) if l == -1: return -1 r = check_int(root.right) if r == -1: return -1 if abs(l - r) > 1: return -1 return max(l, r) + 1 return check_int(root) != -1 if __name__ == '__main__': subroot = Node(2) subroot.left = Node(3) subroot.left.left = Node(4) subroot.left.right = Node(4) root = Node(1) root.right = Node(2) root.left = subroot print(is_balanced(root)) r = Node(2) r.left = Node(2) r.right = Node(2) r.right.right = Node(3) r.left.right = Node(4) print(is_balanced(r))
def identical_trees(self, tree_1, tree_2): if tree_1 is None and tree_2 is None: return True if tree_1 is not None and tree_2 is not None: return ((tree_1.value == tree_2.value) and self.identical_trees(tree_1.left, tree_2.left) and self.identical_trees(tree_1.right, tree_2.right)) return False S = Solution() root1 = Treenode(1) root1.left = Treenode(2) root1.right = Treenode(3) root1.left.left = Treenode(4) root1.left.right = Treenode(5) print root1 root2 = Treenode(1) root2.left = Treenode(2) root2.right = Treenode(3) root2.left.left = Treenode(4) root2.left.right = Treenode(5) print root2 if S.identical_trees(root1, root2): print "Trees are identical" else: print "Trees are not identical"
def test_tree_properties(): root = Node(1) assert root.properties == { 'height': 0, 'is_balanced': True, 'is_bst': True, 'is_complete': True, 'is_max_heap': True, 'is_min_heap': True, 'is_perfect': True, 'is_strict': True, 'leaf_count': 1, 'max_leaf_depth': 0, 'max_node_value': 1, 'min_leaf_depth': 0, 'min_node_value': 1, 'size': 1 } assert root.height == 0 assert root.is_balanced is True assert root.is_bst is True assert root.is_complete is True assert root.is_max_heap is True assert root.is_min_heap is True assert root.is_perfect is True assert root.is_strict is True assert root.leaf_count == 1 assert root.max_leaf_depth == 0 assert root.max_node_value == 1 assert root.min_leaf_depth == 0 assert root.min_node_value == 1 assert root.size == len(root) == 1 root.left = Node(2) assert root.properties == { 'height': 1, 'is_balanced': True, 'is_bst': False, 'is_complete': True, 'is_max_heap': False, 'is_min_heap': True, 'is_perfect': False, 'is_strict': False, 'leaf_count': 1, 'max_leaf_depth': 1, 'max_node_value': 2, 'min_leaf_depth': 1, 'min_node_value': 1, 'size': 2 } assert root.height == 1 assert root.is_balanced is True assert root.is_bst is False assert root.is_complete is True assert root.is_max_heap is False assert root.is_min_heap is True assert root.is_perfect is False assert root.is_strict is False assert root.leaf_count == 1 assert root.max_leaf_depth == 1 assert root.max_node_value == 2 assert root.min_leaf_depth == 1 assert root.min_node_value == 1 assert root.size == len(root) == 2 root.right = Node(3) assert root.properties == { 'height': 1, 'is_balanced': True, 'is_bst': False, 'is_complete': True, 'is_max_heap': False, 'is_min_heap': True, 'is_perfect': True, 'is_strict': True, 'leaf_count': 2, 'max_leaf_depth': 1, 'max_node_value': 3, 'min_leaf_depth': 1, 'min_node_value': 1, 'size': 3 } assert root.height == 1 assert root.is_balanced is True assert root.is_bst is False assert root.is_complete is True assert root.is_max_heap is False assert root.is_min_heap is True assert root.is_perfect is True assert root.is_strict is True assert root.leaf_count == 2 assert root.max_leaf_depth == 1 assert root.max_node_value == 3 assert root.min_leaf_depth == 1 assert root.min_node_value == 1 assert root.size == len(root) == 3 root.left.left = Node(4) assert root.properties == { 'height': 2, 'is_balanced': True, 'is_bst': False, 'is_complete': True, 'is_max_heap': False, 'is_min_heap': True, 'is_perfect': False, 'is_strict': False, 'leaf_count': 2, 'max_leaf_depth': 2, 'max_node_value': 4, 'min_leaf_depth': 1, 'min_node_value': 1, 'size': 4 } assert root.height == 2 assert root.is_balanced is True assert root.is_bst is False assert root.is_complete is True assert root.is_max_heap is False assert root.is_min_heap is True assert root.is_perfect is False assert root.is_strict is False assert root.leaf_count == 2 assert root.max_leaf_depth == 2 assert root.max_node_value == 4 assert root.min_leaf_depth == 1 assert root.min_node_value == 1 assert root.size == len(root) == 4 root.right.left = Node(5) assert root.properties == { 'height': 2, 'is_balanced': True, 'is_bst': False, 'is_complete': False, 'is_max_heap': False, 'is_min_heap': False, 'is_perfect': False, 'is_strict': False, 'leaf_count': 2, 'max_leaf_depth': 2, 'max_node_value': 5, 'min_leaf_depth': 2, 'min_node_value': 1, 'size': 5 } assert root.height == 2 assert root.is_balanced is True assert root.is_bst is False assert root.is_complete is False assert root.is_max_heap is False assert root.is_min_heap is False assert root.is_perfect is False assert root.is_strict is False assert root.leaf_count == 2 assert root.max_leaf_depth == 2 assert root.max_node_value == 5 assert root.min_leaf_depth == 2 assert root.min_node_value == 1 assert root.size == len(root) == 5 root.right.left.left = Node(6) assert root.properties == { 'height': 3, 'is_balanced': False, 'is_bst': False, 'is_complete': False, 'is_max_heap': False, 'is_min_heap': False, 'is_perfect': False, 'is_strict': False, 'leaf_count': 2, 'max_leaf_depth': 3, 'max_node_value': 6, 'min_leaf_depth': 2, 'min_node_value': 1, 'size': 6 } assert root.height == 3 assert root.is_balanced is False assert root.is_bst is False assert root.is_complete is False assert root.is_max_heap is False assert root.is_min_heap is False assert root.is_perfect is False assert root.is_strict is False assert root.leaf_count == 2 assert root.max_leaf_depth == 3 assert root.max_node_value == 6 assert root.min_leaf_depth == 2 assert root.min_node_value == 1 assert root.size == len(root) == 6 root.left.left.left = Node(7) assert root.properties == { 'height': 3, 'is_balanced': False, 'is_bst': False, 'is_complete': False, 'is_max_heap': False, 'is_min_heap': False, 'is_perfect': False, 'is_strict': False, 'leaf_count': 2, 'max_leaf_depth': 3, 'max_node_value': 7, 'min_leaf_depth': 3, 'min_node_value': 1, 'size': 7 } assert root.height == 3 assert root.is_balanced is False assert root.is_bst is False assert root.is_complete is False assert root.is_max_heap is False assert root.is_min_heap is False assert root.is_perfect is False assert root.is_strict is False assert root.leaf_count == 2 assert root.max_leaf_depth == 3 assert root.max_node_value == 7 assert root.min_leaf_depth == 3 assert root.min_node_value == 1 assert root.size == len(root) == 7
if node.right: nxt_lvl.append(node.right) cur_lvl.append(node.data) ret.append(cur_lvl) deq = nxt_lvl return ret if __name__ == '__main__': # Ugly but I'm building a binary tree here with depth 5 # Letters and tree come from image in the epi book k = Node(1) k.left = Node(401) k.left.right = Node(641) k.right = Node(257) j = Node(2, right=k) i = Node(6, left=j) i.right = Node(271) i.right.right = Node(28) c = Node(271) c.left = Node(28) c.right = Node(0) f = Node(561) f.right = Node(3) f.right.left = Node(17) b = Node(6, left=c, right=f) root = Node(314, left=b, right=i) tree = BinaryTree(root) t = compute(tree)
''' (1)-- Root Node / \ / \ (2)L.C (3)Right Child ''' from binarytree import Node root = Node(3) root.left = Node(6) root.right = Node(8) # binary tree print('Binary Tree: ', root) # list of nodes print('List of nodes : ', list(root)) # inorder of nodes print('Inorder of nodes: ', root.inorder) # tree properties print('Size of tree: ', root.size) print('Height of tree: ', root.height) print('Tree Complete? : ', root.is_complete) print('Tree Perfect? : ', root.is_perfect) print('Tree Balanced? : ', root.is_balanced)
return is_bst_valid_rec(root.left, min_val, root.value) and is_bst_valid_rec( root.right, root.value, max_val) def is_bst_valid(root): #return is_bst_valid_rec(root, float('-inf'), float('inf')) return is_bst_valid_inorder(root) bst_tree = bst(height=3) print(bst_tree) test('valid_bst', is_bst_valid(bst_tree), True) non_bst = tree(height=3) print(non_bst) test('invalid bst - simple', is_bst_valid(non_bst), False) non_bst_complex = Node(4) non_bst_complex.left = Node(2) non_bst_complex.left.left = Node(1) non_bst_complex.left.right = Node(3) non_bst_complex.left.right.left = Node(1) #non_bst_complex.left.right.right = Node(6) non_bst_complex.right = Node(5) print(non_bst_complex) test('invalid bst - more complex', is_bst_valid(non_bst_complex), False)
def create_tree(self, nums, root, i): if i < len(nums): root = TN(nums[i]) root.left = self.create_tree(nums, root.left, 2 * i + 1) root.right = self.create_tree(nums, root.right, 2 * i + 2) return root
from binarytree import Node root = Node(6) root.left = Node(3) root.right = Node(8) leaf = Node(8) leaf.right = Node(10) root.right = leaf leaf = Node(10) leaf.left = Node(9) root.right = leaf # Getting binary tree print('Binary tree :', root) # Getting list of nodes print('List of nodes :', list(root)) # Getting inorder of nodes print('Inorder of nodes :', root.inorder) # Checking tree properties print('Size of tree :', root.size) print('Height of tree :', root.height) # Get all properties at once print('Properties of tree : \n', root.properties)
if len(depths) == 2: return abs(depths[0] - depths[1]) <= 1 if len(depths) > 2: return False else: # traverse first left side then right side if node.left: nodes.append((node.left, depth + 1)) if node.right: nodes.append((node.right, depth + 1)) return True print "Perfect Tree" root = tree(height=4, is_perfect=True) print root print is_tree_perfect(root) print "Not Perfect Tree" root = Node(1) root.left = Node(2) root.right = Node(3) root.left.right = Node(4) root.left.right.left = Node(5) print root print is_tree_perfect(root)
else: current.value = int(char) return root numbers = [] with open('input.txt', 'r') as file: numbers = [_.strip() for _ in file.readlines()] root = parse_number(numbers[0]) for number in numbers[1:]: root = Node(-1, left=root) root.right = parse_number(number) reduce = True while reduce: if len(root.levels) > 5: did_explode = False for node in root.levels[-2]: if not did_explode: if node.left != None: left = node.left index = list(reversed(root.postorder)).index(left) for next_left in list(reversed(root.postorder))[index + 1:]: if next_left.value > -1: next_left.value += left.value break
if not root: return 0 return max(self.longest(root.left, root.value), self.longest(root.right, root.value), self.longestConsecutive(root.left), self.longestConsecutive(root.right)) def longest(self, root, value): if not root or root.value != value + 1: return 1 return 1 + max(self.longest(root.right, root.value), self.longest(root.left, root.value)) root = Node(1) root.right = Node(3) root.right.left = Node(2) root.right.right = Node(4) root.right.right.right = Node(5) root2 = Node(2) root2.right = Node(3) root2.right.left = Node(2) root2.right.left.left = Node(1) print root print root2 print Solution().longestConsecutive(root) print Solution().longestConsecutive(root2)
def test_subtree(): def self_subtree(target, node_id): return target.subtree(node_id) for invalid_tree in ['foo', -1, None]: with pytest.raises(ValueError) as err: subtree(invalid_tree, 0) assert str(err.value) == 'Expecting a list or a node' for subtree_func in [subtree, self_subtree]: root = Node(1) for invalid_id in ['foo', None]: with pytest.raises(ValueError) as err: subtree_func(root, invalid_id) assert str(err.value) == 'The node ID must be an integer' with pytest.raises(ValueError) as err: subtree_func(root, -1) assert str(err.value) == 'The node ID must start from 0' assert subtree_func(root, 0) == root for invalid_id in [1, 2, 3, 4, 5]: with pytest.raises(ValueError) as err: subtree_func(root, invalid_id) assert str(err.value) == \ 'Cannot find node with ID {}'.format(invalid_id) root.left = Node(2) assert subtree_func(root, 0) == root assert subtree_func(root, 1) == root.left for invalid_id in [2, 3, 4, 5]: with pytest.raises(ValueError) as err: subtree_func(root, invalid_id) assert str(err.value) == \ 'Cannot find node with ID {}'.format(invalid_id) root.right = Node(3) assert subtree_func(root, 0) == root assert subtree_func(root, 1) == root.left assert subtree_func(root, 2) == root.right for invalid_id in [3, 4, 5]: with pytest.raises(ValueError) as err: subtree_func(root, invalid_id) assert str(err.value) == \ 'Cannot find node with ID {}'.format(invalid_id) root.left.right = Node(4) assert subtree_func(root, 0) == root assert subtree_func(root, 1) == root.left assert subtree_func(root, 2) == root.right assert subtree_func(root, 3) == root.left.right for invalid_id in [4, 5]: with pytest.raises(ValueError) as err: subtree_func(root, invalid_id) assert str(err.value) == \ 'Cannot find node with ID {}'.format(invalid_id) root.left.left = Node(5) assert subtree_func(root, 0) == root assert subtree_func(root, 1) == root.left assert subtree_func(root, 2) == root.right assert subtree_func(root, 3) == root.left.left assert subtree_func(root, 4) == root.left.right for invalid_id in [5, 6]: with pytest.raises(ValueError) as err: subtree_func(root, invalid_id) assert str(err.value) == \ 'Cannot find node with ID {}'.format(invalid_id)
def k_path_sum(self, root, k): if root is None: return #print 'Visiting {}'.format(root.value) self.path.append(root.value) self.k_path_sum(root.left, k) self.k_path_sum(root.right, k) #print 'Current path: {}'.format(self.path) currsum = 0 for i in reversed(xrange(len(self.path))): currsum += self.path[i] if currsum == k: print self.path[i:] self.path.pop() root = Treenode(1) root.left = Treenode(3) root.left.left = Treenode(2) root.left.right = Treenode(1) root.left.right.left = Treenode(1) root.right = Treenode(-1) root.right.left = Treenode(4) root.right.left.left = Treenode(1) root.right.left.right = Treenode(2) root.right.right = Treenode(5) root.right.right.right = Treenode(2) print(root) S = Solution() S.k_path_sum(root, 5)
#缓存节点 preNode = t convert(t.right, preNode) def ConvertTree2List(t): if t == None: return None preNode = None convert(t, preNode) #t 在中间,升序需要从左边去查找 cur = t.left while cur != None: cur = cur.left return cur t = Node(10) t.left = Node(6) t.right = Node(14) t.left.left = Node(4) t.left.right = Node(8) t.right.left = Node(12) t.right.right = Node(16) #print(t) re = ConvertTree2List(t) Print(re)
from binarytree import Node, tree root = Node(7) root.left = Node(3) root.right = Node(9) root.left.left = Node(1) root.left.right = Node(5) root.left.right.left = Node(4) root.left.right.right = Node(6) root.right.right = Node(11) root.right.left = Node(8) # _5__ # / \ # 3 8 # / \ / \ # 1 4 7 9
self.pushAll(root) # @return a boolean, whether we have a next smallest number def hasNext(self): if self.stack: return True return False # @return an integer, the next smallest number def next(self): tmpNode = self.stack.pop() self.pushAll(tmpNode.right) return tmpNode.value def pushAll(self, node): while node is not None: self.stack.append(node) node = node.left root = Treenode(2) root.left = Treenode(1) root.left.left = Treenode(0) root.right = Treenode(3) print(root) S = Solution(root) print S.next() print S.next() print S.hasNext()
def test_inspect(): for invalid_argument in [None, 1, 'foo']: with pytest.raises(ValueError) as err: inspect(invalid_argument) assert str(err.value) == 'Expecting a list or a node' def convert_inspect(target): return inspect(convert(target)) def self_inspect(target): return target.inspect() for inspect_func in [inspect, convert_inspect, self_inspect]: root = Node(1) assert inspect_func(root) == { 'is_height_balanced': True, 'is_weight_balanced': True, 'is_max_heap': True, 'is_min_heap': True, 'is_bst': True, 'is_full': True, 'height': 0, 'max_value': 1, 'min_value': 1, 'leaf_count': 1, 'node_count': 1, 'max_leaf_depth': 0, 'min_leaf_depth': 0, } root.left = Node(2) assert inspect_func(root) == { 'is_height_balanced': True, 'is_weight_balanced': True, 'is_max_heap': False, 'is_min_heap': True, 'is_bst': False, 'is_full': False, 'height': 1, 'max_value': 2, 'min_value': 1, 'node_count': 2, 'leaf_count': 1, 'max_leaf_depth': 1, 'min_leaf_depth': 1, } root.right = Node(3) assert inspect_func(root) == { 'is_height_balanced': True, 'is_weight_balanced': True, 'is_max_heap': False, 'is_min_heap': True, 'is_bst': False, 'is_full': True, 'height': 1, 'max_value': 3, 'min_value': 1, 'leaf_count': 2, 'node_count': 3, 'max_leaf_depth': 1, 'min_leaf_depth': 1, } root.value = 2 root.left.value = 1 root.right.value = 3 assert inspect_func(root) == { 'is_height_balanced': True, 'is_weight_balanced': True, 'is_max_heap': False, 'is_min_heap': False, 'is_bst': True, 'is_full': True, 'height': 1, 'max_value': 3, 'min_value': 1, 'leaf_count': 2, 'node_count': 3, 'max_leaf_depth': 1, 'min_leaf_depth': 1, } root.value = 1 root.left.value = 2 root.right.value = 3 root.left.right = Node(4) assert inspect_func(root) == { 'is_height_balanced': True, 'is_weight_balanced': True, 'is_max_heap': False, 'is_min_heap': False, 'is_bst': False, 'is_full': False, 'height': 2, 'max_value': 4, 'min_value': 1, 'leaf_count': 2, 'node_count': 4, 'max_leaf_depth': 2, 'min_leaf_depth': 1, } root.left.left = Node(5) assert inspect_func(root) == { 'is_height_balanced': True, 'is_weight_balanced': True, 'is_max_heap': False, 'is_min_heap': True, 'is_bst': False, 'is_full': True, 'height': 2, 'max_value': 5, 'min_value': 1, 'leaf_count': 3, 'node_count': 5, 'max_leaf_depth': 2, 'min_leaf_depth': 1, } root.right.right = Node(6) assert inspect_func(root) == { 'is_height_balanced': True, 'is_weight_balanced': True, 'is_max_heap': False, 'is_min_heap': False, 'is_bst': False, 'is_full': False, 'height': 2, 'max_value': 6, 'min_value': 1, 'leaf_count': 3, 'node_count': 6, 'max_leaf_depth': 2, 'min_leaf_depth': 2, } root.right.right = Node(None) with pytest.raises(ValueError) as err: assert inspect_func(root) assert str(err.value) == 'A node cannot have a null value' root.right.right = {} with pytest.raises(ValueError) as err: assert inspect_func(root) assert str(err.value) == 'Found an invalid node in the tree'
""" deque: double-ended queue """ # Build a tree with binarytree.tree seed(3) my_tree = tree(height = 3, is_perfect = False) #print("Generate with built-in tree method") #print(type(my_tree)) # <class 'binarytree.Node'> #print(my_tree) # Build with Node root = Node(1) root.left = Node(2) root.right = Node(3) #print("Generate with built-in Node method") #print(root) #print(root.value) # Build tree using a list data1 = [10,5,-3,3,2,None,11,3,-2,None,1] data2 = [3,5,2,1,4,6,7,8,9,10,11,12,13,14] def create_btree_with_list(data): tree = Node(data.pop(0)) fringe = deque([tree]) while len(data) > 1: # take out the first item in the queue as the parent node