Interview must: Pre-order, middle-order, post-order traversal of binary tree, and reconstruction of binary tree by using front-middle, middle-back sequence, with python implementation code and examples

concept:

The traversal naming is named
according to the location where the access node operation occurs:

① NLR: Preorder Traversal (also known as Preorder Traversal)

-The operation of visiting the root node occurs before traversing its left and right subtrees.

② LNR: Inorder Traversal

——The operation of visiting the root node occurs in (between) traversing the left and right subtrees.

③ LRN: Postorder Traversal

-The operation of visiting the root node occurs after traversing its left and right subtrees.

Common feature: In the three traversal methods, the order of the leaf nodes is the same from left to right.

For example:

Reminder: You can understand the traversal sequence according to the code, and then walk through this picture yourself.

Insert picture description here

Traversal algorithm:

1. Preorder traversal

The definition of the recursive algorithm of first (root, previous) order traversal:

If the binary tree is not empty, perform the following operations in sequence:
(1) Visit the root node;
(2) Traverse the left subtree;
(3) Traverse the right subtree.

Pre-order traversal of python code:

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        def forward(root1):
            if not root1:
                return 
            ans.append(root1.val)
            forward(root1.left)
            forward(root1.right)
        ans = []
        forward(root)
        return ans

2. In-order traversal

The definition of recursive algorithm for middle (root) order traversal:

If the binary tree is not empty, perform the following operations in sequence:
(1) Traverse the left subtree;
(2) Visit the root node;
(3) Traverse the right subtree.

In order to traverse the python code:

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        def middle(root1):
            if not root1:
                return 
            middle(root1.left)
            ans.append(root1.val)
            middle(root1.right)
        
        ans = []
        middle(root)
        return ans

3. Post-order traversal

The definition of the recursive algorithm after (root) order traversal:

If the binary tree is not empty, perform the following operations in sequence:
(1) Traverse the left subtree;
(2) Traverse the right subtree;
(3) Visit the root node.

Traverse the python code in post-order:

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        def backward(root1):
            if not root1:
                return 
            backward(root1.left)
            backward(root1.right)
            ans.append(root1.val)
        
        ans = []
        backward(root)
        return ans

4. Use the front and middle traversal sequence to reconstruct the binary tree

Idea : The first element of the pre-order traversal must be the root node, and then by finding the position of the middle-order root node in the middle-order traversal, the distribution of the left and right leaves can be judged (in the middle-order traversal, the left leaves of the root node are all left leaves , All right leaves behind).

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
        if len(preorder)==0:
            return
        root = TreeNode(preorder[0])  # 根节点肯定是前序遍历的第一个
        root_index = inorder.index(preorder[0])  # 返回中序遍历中根节点的位置,该位置之前全是左叶子,之后全是右叶子。注意前序和中序遍历序列中,左右叶子的长度肯定相同
        root.left = self.buildTree(preorder[1:root_index+1], inorder[:root_index])
        root.right = self.buildTree(preorder[root_index+1:], inorder[root_index+1:])
        return root

5. Reconstruct the binary tree using the middle and post traversal sequence

Idea : The last element of the post-order traversal must be the root node, and then by finding the position of the middle-order root node in the middle-order traversal, the distribution of the left and right leaves can be judged (in the middle-order traversal, the left leaves of the root node are all left. All right leaves behind). Finally, the distribution of post-order traversal is judged according to the length of the left and right leaves in the middle order (in post-order traversal, all the left leaves are distributed to the left, and all the right leaves are all on the right)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        if not postorder:
            return None
        root = TreeNode(postorder[-1])  # 后序最后一个节点是根节点
        n = inorder.index(root.val)  # 取出中序中根节点的index,可以快速判别左右子树
        root.left = self.buildTree(inorder[:n], postorder[:n])  # 在中序中,根节点的左子树元素都在左边;在后序中,根节点的右子树元素也都在左边
        root.right = self.buildTree(inorder[n+1:], postorder[n:-1])  # 在中序中,根节点的右子树元素都在右边;在后序中,也都在左边,但是就不取最后一个元素了,因为最后一个是根
        return root

Note: It is not possible to reconstruct a unique binary tree using the front and back traversal sequence

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/114646712