return None if k == n: lst.append(root.val) if root is not None: k = k + 1 traverse(root.leftChild, k, n, lst) traverse(root.rightChild, k, n, lst) return lst def findKNodes(root, n): k = 0 lst = [] lst = traverse(root, k, n, lst) return lst bst = BinarySearchTree(6) bst.insert(4) bst.insert(2) bst.insert(5) bst.insert(9) bst.insert(8) bst.insert(12) bst.insert(10) bst.insert(14) print(findKNodes(bst.root, 2))
from tree.BinarySearchTree import BinarySearchTree import random from tree.bst_display import display BST = BinarySearchTree(50) for _ in range(15): ele = random.randint(0, 100) BST.insert(ele) # We have hidden the code for this function but it is available for use! display(BST.root) print('\n') print(BST.search(15)) print(BST.search(50))
first_line = s + x * '_' + (n - x) * ' ' second_line = (u + x) * ' ' + '\\' + (n - x - 1) * ' ' shifted_lines = [u * ' ' + line for line in lines] final_lines = [first_line, second_line] + shifted_lines return final_lines, n + u, p + 2, u // 2 # Two children. left, n, p, x = _display_aux(node.leftChild) right, m, q, y = _display_aux(node.rightChild) s = '%s' % node.val u = len(s) first_line = (x + 1) * ' ' + (n - x - 1) * \ '_' + s + y * '_' + (m - y) * ' ' second_line = x * ' ' + '/' + \ (n - x - 1 + u + y) * ' ' + '\\' + (m - y - 1) * ' ' if p < q: left += [n * ' '] * (q - p) elif q < p: right += [m * ' '] * (p - q) zipped_lines = zip(left, right) lines = [first_line, second_line] + \ [a + u * ' ' + b for a, b in zipped_lines] return lines, n + m + u, max(p, q) + 2, n + u // 2 BST = BinarySearchTree(15) for _ in range(15): ele = random.randint(0,100) BST.insert(ele) display(BST.root)
from tree.BinarySearchTree import BinarySearchTree from tree.bst_display import display bst = BinarySearchTree(50) bst.insert_rec(31) bst.insert(9) bst.insert(32) bst.insert(5) bst.insert(23) bst.insert(54) bst.insert(62) bst.insert(57) bst.insert(78) bst.insert(63) bst.insert(75) display(bst.root) bst.delete(9) display(bst.root) bst.delete(62) display(bst.root)
from tree.BinarySearchTree import BinarySearchTree from tree.bst_display import display from tree.Node import Node def findHeight(root): if root is None: # check if root exists return -1 # no root means -1 height else: max_sub_tree_height = max(findHeight( root.leftChild), findHeight( root.rightChild)) # find the max height of the two sub-tree # add 1 to max height and return return 1 + max_sub_tree_height BST = BinarySearchTree(6) BST.insert(4) BST.insert(9) BST.insert(5) BST.insert(2) BST.insert(8) BST.insert(12) BST.insert(10) BST.insert(14) display(BST.root) print(findHeight(BST.root))