[python] Level traversal of binary trees & list representation


  In addition to pre-order, mid-order, and post-order traversal, there is also a top-to-bottom, left-to-right level traversal method in a binary tree . This method is more in line with human visual intuition and has excellent performance in scenarios such as calculating the maximum depth of a tree, returning the outermost leaf node, and returning a list representation of a binary tree.
   List representation is the most important representation method besides binary tree graphical representation , and can be implemented through hierarchical traversal.

1. Create a binary tree

Refer to the creation of a binary tree to build a binary tree:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

node4 = TreeNode(1)
node5 = TreeNode(4)
node6 = TreeNode(6)
node7 = TreeNode(9)
node2 = TreeNode(3, node4, node5)
node3 = TreeNode(7, node6, node7)
node1 = TreeNode(5, node2, node3)
root = node1

Binary tree

2. Level traversal

2.1 Detailed code explanation

  • If the root node is empty, an empty list is returned.
  • Level and Next record the current level node and the next level node respectively.
  • Vals and Res record the value of the current layer and the values ​​of all layers respectively. Res is the accumulation of Vals.
  • Looping the current node Level, you can get the value Vals of the current layer and the node Next of the next layer.
  • When Next is empty, the traversal ends, the while loop exits, and the Res two-dimensional array is returned.
def levelTraversal(root):
    if not root:
        return []
    Level = [root]   # 当前遍历层
    Res = []        # 层次遍历返回结果
    while True:
        Vals = []   # 当前层节点的值
        Next = []   # 下一层的节点
        for node in Level:
            Vals.append(node.val)
            if node.left is not None:   # 若存在左子节点,计入到下一层
                Next.append(node.left)
            if node.right is not None:  # 若存在右子节点,计入到下一层
                Next.append(node.right)
        Res.append(Vals)
        if len(Next) == 0:  # 如果下一层没有节点,说明遍历完成
            break
        else:
            Level = Next
    return Res

Run the function and return a two-dimensional list expression:

>>> print(levelTraversal(root))
>>> [[5], [3, 7], [1, 4, 6, 9]]

Although two-dimensional list expressions can be used for traversal, they can only represent binary trees in one direction and cannot restore the structure of binary trees. Therefore, other methods need to be used in the third part.

2.2 Concise writing

def levelTraversal(root):
    if not root:
        return []
    Level, Res = [root], []
    while Level:
        Vals, Next = [], []
        for node in Level:
            Vals.append(node.val)
            if node.left:
                Next.append(node.left)
            if node.right:
                Next.append(node.right)
        Res.append(Vals)
        Level = Next
    return Res

3. List representation

List expressions have a one-to-one correspondence with binary trees and are one of the most common expressions of binary trees. The two can be converted to each other.

3.1 Rule description

When traversing from top to bottom and left to right:

  • If the parent node has only one child node, use "null" in the missing left/right child node position.
  • If it is the leaf node of the last layer and lacks left and right child nodes, then the child nodes are all "null", so the abbreviation can be omitted.

Insert image description here
As shown above:

  • The first level is the root node, so the list expression starts with[7]
  • The second level is a full level, so the list expression of this level is[3,9]
  • In the third level, the left and right child nodes of 9 are empty and filled with "null". The expression of this level is[1,4,null,null]
  • In the fourth level, the child node of 1 and the left child node of 4 are empty and filled with "null". The expression of this level is[null,null,null,5]
  • In the fifth level, the left child node of 5 is empty and filled with "null". The expression of this level is[null,6]
  • At this point, the last layer has been reached and no more filling is needed. The final expression can be obtained by directly connecting the above layers in series:
    [7,3,9,1,4,null,null,null,null,null,5,null,6]

3.2 Code implementation

'''
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
        
node7 = TreeNode(6)
node6 = TreeNode(5, None, node7)
node5 = TreeNode(4, None, node6)
node4 = TreeNode(1)
node3 = TreeNode(9)
node2 = TreeNode(3, node4, node5)
node1 = TreeNode(7, node2, node3)
root = node1
'''
def listExpress(root):
    if not root:
        return []
    Level = [root]
    Expre = [root.val]
    while True:
        Next = []
        for node in Level:
            if node.left:
                Expre.append(node.left.val)
                Next.append(node.left)
            else:
                Expre.append("null")
            if node.right:
                Expre.append(node.right.val)
                Next.append(node.right)
            else:
                Expre.append("null")
        if not Next:
            return Expre[:len(Expre) - len(Level) * 2]
        Level = Next

Function call:

>>> print(listExpress(root))
>>> [7, 3, 9, 1, 4, 'null', 'null', 'null', 'null', 'null', 5, 'null', 6]

Guess you like

Origin blog.csdn.net/weixin_44844635/article/details/131641514