[Brush question diary] Verify the preorder serialization of binary trees

Continue to create, accelerate growth! This is the 5th day of my participation in the "Nuggets Daily New Plan · June Update Challenge", click to view the event details

The 51st article of this brushing diary is titled: Verifying the preorder serialization of binary trees , medium

1. Topic description:

Another binary tree problem, how about a binary tree problem, is it simpler than a multi-fork tree? Actually, they have the same solution

2. What idea does this question examine? What is your thinking?

The requirements of the title are relatively clear, that is, to give a string containing numbers, commas, and pound signs, which respectively represent binary tree nodes, character intervals, and empty nodes

Then we check in some way that the given string is the result of the preorder traversal of the binary tree

When you see this requirement, you may actually smile. Can we simply restore the string to a binary tree according to the preorder traversal method?

But the title specifically emphasizes that we can't rebuild the tree, so we can only find another way

analyze

After a little thinking, our attention can be shifted to the number of certain characters in the string, let's take a look at the figure below

For a binary tree, a node may have 2 child nodes or 1 child node, then according to the meaning of the title, it may be to add two specific numbers in the string, such as 2,3

or an empty node # number and 1 number, eg #,3 or 3,#

Then when we traverse the string, if we encounter a # sign, then we subtract 1 from the number of nodes to be supplemented, if it is a number, then subtract 1 from the number of nodes to be supplemented, and Continue to add 2 nodes in

Here we can't directly confuse the number of nodes to be supplemented in the previous layer with the number of nodes to be supplemented in this layer, it needs to be separated

In this way, our focus is on the characters to be placed in the given string. We traverse from the beginning and record the characters that need to be supplemented according to the above logic.

We can use the stack method to deal with it and continue to traverse. If we encounter the # sign, we subtract 1 from the number of nodes to be supplemented (the number at the top of the stack). If it is a number, then we still subtract the number of nodes to be supplemented. Subtract 1, and continue to add 2 nodes to the stack

  • During the traversal process, if we have not completed the traversal of the string given by the question, but the nodes to be supplemented are no longer available, it means that the given string does not meet the requirements.
  • Of course, if you traverse the complete string and find that the number of nodes to be supplemented is still recorded, then there is also a problem, indicating that the string is not a complete binary tree preorder traversal.
  • Therefore, we can only determine that the string is a complete binary tree preorder traversal only when we have completely traversed the string and the number of nodes to be added is also 0.

3. Coding

According to the above logic and analysis, we can translate it into the following code

It should be noted here that when we initialize the nodes to be supplemented, one node is given by default, because we need to put the root node, and there is only one root node.

The encoding is as follows:

func isValidSerialization(preorder string) bool {
    n := len(preorder)
    help := []int{1}
    // 遍历给出的 字符串
    for i := 0; i < n; {
        if len(help) == 0 {
            return false
        }
        // 校验字符串中给出的 3 中情况,数字,逗号,# 号
        if preorder[i] == ',' {
            i++
        } else if preorder[i] == '#' {
            help[len(help)-1]--
            if help[len(help)-1] == 0 {
                help = help[:len(help)-1]
            }
            i++
        } else {
            for i < n && preorder[i] != ',' {
                i++
            }
            help[len(help)-1]--
            if help[len(help)-1] == 0 {
                help = help[:len(help)-1]
            }
            help = append(help, 2)
        }
    }
    return len(help) == 0
}
复制代码

4. Summary:

The time complexity is very clear, we traverse the given string once, so the time complexity is O(n) , and the space complexity is also O(n) , because we open up the stack space, this space will involve every binary tree. a node

Original title address: 331. Verify the preorder serialization of binary trees

I am here today, what I have learned, if there are any deviations, please correct me

Welcome to like, follow, favorite

Friends, your support and encouragement are the motivation for me to persist in sharing and improve quality

Okay, here it is this time

Technology is open, and our mentality should be open. Embrace change, live in the sun, and move forward.

I'm the little devil boy Nezha , welcome to like, follow and collect, see you next time~

Guess you like

Origin juejin.im/post/7103925525525053471