算法分析
树的遍历
1 class Node: # This is the Class Node with constructor that contains data variable to type data and left,right pointers. 2 def __init__(self, data): 3 self.data = data 4 self.left = None 5 self.right = None 6 7 def display(tree): #In Order traversal of the tree 8 9 if tree is None: 10 return 11 12 if tree.left is not None: 13 14 display(tree.left) 15 16 print(tree.data) 17 18 if tree.right is not None: 19 display(tree.right) 20 21 return 22 23 def depth_of_tree(tree): #This is the recursive function to find the depth of binary tree. 24 if tree is None: 25 return 0 26 else: 27 depth_l_tree = depth_of_tree(tree.left) 28 depth_r_tree = depth_of_tree(tree.right) 29 if depth_l_tree > depth_r_tree: 30 return 1 + depth_l_tree 31 else: 32 return 1 + depth_r_tree 33 34 35 def is_full_binary_tree(tree): # This functions returns that is it full binary tree or not? 36 if tree is None: 37 return True 38 if (tree.left is None) and (tree.right is None): 39 return True 40 if (tree.left is not None) and (tree.right is not None): 41 return (is_full_binary_tree(tree.left) and is_full_binary_tree(tree.right)) 42 else: 43 return False 44 45 46 def main(): # Main func for testing. 47 tree = Node(1) 48 tree.left = Node(2) 49 tree.right = Node(3) 50 tree.left.left = Node(4) 51 tree.left.right = Node(5) 52 tree.left.right.left = Node(6) 53 tree.right.left = Node(7) 54 tree.right.left.left = Node(8) 55 tree.right.left.left.right = Node(9) 56 57 print(is_full_binary_tree(tree)) 58 print(depth_of_tree(tree)) 59 print("Tree is: ") 60 display(tree) 61 62 63 if __name__ == '__main__': 64 main() 65