How to generate a binary tree in the LeetCode topic? Generate a binary tree from a given ordered list (python)

When brushing leetcode binary tree related topics, there are often such given examples, for example: check balance

实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
    3
   / \
  9  20
    /  \
   15   7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
      1
     / \
    2   2
   / \
  3   3
 / \
4   4
返回 false 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/check-balance-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

If we want to debug the program locally, we need to generate the corresponding binary tree to debug the code. However, it is very cumbersome to manually add Nodes every time to generate a tree.

According to the example, what we are given is a hierarchical ordered list similar to [3,9,20,null,null,15,7]. We can intuitively know that 3 is the root node, 9 and 20 are the left and right child nodes of 3, null and null are the left and right child nodes of 9, and 15 and 7 are the left and right child nodes of 20.
From the above description, it can be found that the order of assigning the left and right nodes is also 3, 9, 20, which is consistent with the order of the list , that is, first assign the left and right nodes to 3, then assign the left and right nodes to 9, and then assign the left and right nodes to 20, If the list was longer, then null would be skipped , 15 would be assigned left and right nodes, and 7 would be assigned left and right nodes.
Therefore, we can use queues to implement the first-in-first-out feature in the initialization of binary trees. The following diagram illustrates the process of queue initialization binary tree:

Get 3 and put it in the queue

1

Get 9, assign it to the left son of 3, and put it in the queue

2

Get 20, assign it to the right node of 3, and put it in the queue

3

3 The left and right nodes have been allocated, pop out of the queue

4

Get null, assign it to the left node of 9, note: null will not be put into the queue

5

Get null and assign to the right node of 9

6

9 The left and right nodes have been allocated, pop out of the queue

7

Get 15, assign it to the left son of 20, and put it in the queue

8

Get 7, assign it to the right son of 20, and put it in the queue

9

20 The left and right nodes have been allocated, pop out of the queue

10

There is no new element, so return to the root node 3 at this step.
The final code is as follows:
# 节点类
class Node(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
# 树生成代码
def generate_tree(vals):
    if len(vals) == 0:
        return None
    que = [] # 定义队列
    fill_left = True # 由于无法通过是否为 None 来判断该节点的左儿子是否可以填充,用一个记号判断是否需要填充左节点
    for val in vals:
        node = Node(val) if val is not None else None # 非空值返回节点类,否则返回 None
        if len(que)==0:
            root = node # 队列为空的话,用 root 记录根结点,用来返回
            que.append(node)
        elif fill_left:
            que[0].left = node
            fill_left = False # 填充过左儿子后,改变记号状态
            if node: # 非 None 值才进入队列
                que.append(node)
        else:
            que[0].right = node
            if node:
                que.append(node)
            que.pop(0) # 填充完右儿子,弹出节点
            fill_left = True # 
    return root
# 定义一个dfs打印中序遍历
def dfs(node):
    if node is not None:
        dfs(node.left)
        print(node.val, end=' ')
        dfs(node.right)
# 定义一个bfs打印层序遍历
def bfs(node):
    que = []
    que.append(node)
    while que:
        l = len(que)
        for _ in range(l):
            tmp = que.pop(0)
            print(tmp.val, end=' ')
            if tmp.left:
                que.append(tmp.left)
            if tmp.right:
                que.append(tmp.right)
        print('|', end=' ')

# test
null = None
vals = [3,9,20,null,null,15,7]
tree = generate_tree(vals) 
print('中序遍历:')    
dfs(tree) # 9 3 15 20 7 
print('\n层序遍历:')
bfs(tree) # 3 | 9 20 | 15 7 |

Guess you like

Origin blog.csdn.net/baoxin1100/article/details/108025393