python数据结构之二叉树的建立实例
先建立二叉树节点,有一个data数据域,left,right 两个指针域
# coding:utf-8 class TreeNode(object): def __init__(self,left=None,right=None,data=0): self.left = left self.right = right self.data =data
建立树:
class BTree(object): def __init__(self,root=None): self.root = root
手动建立二叉树
if __name__ == "__main__": node1 = TreeNode(data=1) node2 = TreeNode(node1, None, 2) node3 = TreeNode(data=3) node4 = TreeNode(data=4) node5 = TreeNode(node3, node4, 5) node6 = TreeNode(node2, node5, 6) node7 = TreeNode(node6, None, 7) node8 = TreeNode(data=8) root = TreeNode(node7, node8, 'root') bt = BTree(root)
然后会生成下面的二叉树
# 生成的二叉树 # ------------------------ # root # 7 8 # 6 # 2 5 # 1 3 4 # # -------------------------
除了 手动一个个的制定 node 节点,还可以创建一个 create 方法,接受用户输入添加二叉树节点。。。使用前续方式添加 ,代码如下:
# coding:utf-8 class TreeNode(object): def __init__(self,left=None,right=None,data=0): self.left = left self.right = right self.data =data class BTree(object): def __init__(self,root=None): self.root = root def is_empty(self): return self.root == None def create(self): temp = input('enter a value:') if temp is '#': return None treenode = TreeNode(data=temp) if self.root is None: self.root = treenode treenode.left = self.create() treenode.right = self.create() if __name__ == "__main__": bt = BTree() bt.create()
使用create创建二叉树
#运行文件 在交互解释器下面运行 bt = BTree() bt.create() enter a value:9 enter a value:7 enter a value:6 enter a value:2 enter a value:1 enter a value:'#' enter a value:'#' enter a value:'#' enter a value:5 enter a value:3 enter a value:'#' enter a value:'#' enter a value:4 enter a value:'#' enter a value:'#' enter a value:'#' enter a value:8 enter a value:'#' enter a value:'#'
通过 create 也可以得到同样的效果