Binary tree
-
The root node (root) is the uppermost node
-
Path (path) from the start node to the end node experienced edge
-
Except for the root node, each parent node is its parent node
-
Children (children) each node of the lower node pointed to by the edge
-
Siblings have the same father and are at the same node
-
Subtree (subtree) Each node contains a subtree composed of all its descendants
-
Leaf node (leaf node) Nodes without children become child nodes
Binary tree is a simple and commonly used structure, each node contains two children
Binary tree related concepts -
Node depth (depth) The number of levels corresponding to the node
-
The height of the tree (height) The height of the binary tree is the level number +1, because the level is calculated from zero
-
The width of the number (width) The width of the binary tree refers to the number of nodes with the largest node level.
Full binary tree: If each internal node (non-leaf node) contains two children, it becomes a full binary tree, a
perfect binary tree: all leaf nodes, All at the same level.
Complete binary tree: The perfect binary tree with height h is reduced to h-1, and the bottom slot is filled from left to right, which is
the representation of a complete binary tree. In fact, we find some similarities with the linked list, one node , Need to save the child's pointer to
traverse the binary tree: -
First root order traversal: first process the root, then the left subtree and the right subtree
-
Middle root order traversal: left subtree, processing root, right subtree
-
Post-root order traversal: left subtree, right subtree root
#节点
class BSTNode(object):
def __init__(self,key, value,right = None,left = None):
self.key, self.value,self.right,self.left = key, value , right , left
class BinTree(object):
def __init__(self,root = None):
self.root = root
@classmethod
def build_from(cls,node_list):
"""
通过节点信息构造二叉树
第一次遍历我们的构造 node 节点
第二次遍历给root 和 孩子值
最后我们用root 初始化这个类并返回一个对象
"""
#创建一个空字典
node_dict = {}
#遍历list
for node_data in node_list:
data = node_data['data']
#实例化节点,赋值给字典
node_dict[data] = BSTNode(data)
#第二层次遍历list
for node_data in node_list:
data = node_data['data']
node = node_dict[data]
if node_data['is_root']:
root = node
node.left = node_dict.get(node_data['left'])
node.right = node_dict.get(node_data['right'])
#返回BinTree对象
return cls(root)