算法分析

博客内容为树的遍历相关,转载自https://www.cnblogs.com/binyang/p/10897594.html ,涉及信息技术领域的数据结构中树的操作。

树的遍历

  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 

转载于:https://www.cnblogs.com/binyang/p/10897594.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值