【Binary tree】Verify the preorder serialization of binary tree

0x00 topic

One way to serialize a binary tree is to use 前序遍历
When a 非空node is encountered, the value of this node can be recorded.
If it is a node, the value can be recorded using a tag, e.g.#

Given a sequence 逗号delimited by ,
verify that it is 正确a 前序serialization of a binary tree of ,
write an algorithm that works under the condition of reconstructing the tree

Each comma-separated character, is an integer
or a pointer representing a nullpointer #
You can think that the input format is always valid
e.g. it will never contain two consecutive commas, like1,,3


0x01 Ideas

method one:

First define a concept called槽位

A 槽位can be seen as 被节点填充those positions in the current binary tree that are waiting for

The establishment of a binary tree is also accompanied by changes in the 槽位number . Whenever a node is encountered:
a. If a node , 消耗a slot is required
b. If a 非空node , in addition to 消耗one slot, 补充two more slots are required

Use the stack to maintain the changes
of the slots. Each 元素of the stacks represents the remaining slots at the corresponding node, 数量
and top element of the stack corresponds to the number of slots available in the next step.

When the node , only the top element of the stack is decremented. 1
When the 非空node , the top element of the stack is decremented 1, and then one is pushed into the stack.2

Whenever the element 0on the top of the stack becomes, immediately after the 弹出
traversal of the top of the stack, if the stack 为空
indicates that there is no slot to be filled, it is a 合法sequence

Otherwise, if the stack 不为空is used, the sequence is invalid
. In addition, in the process of traversing, if the number of slots is used 不足, the sequence is invalid.


Method Two:计数

Can the space complexity of method 1 be optimized O(1)to ?
Looking back at the logic of method 1, if the elements in the stack are regarded as one 整体
, that is, all the remaining slots 数量, the slots can also be maintained.变化

Therefore, only one is maintained 计数器, which means that the
rest can remain unchanged


0x02 solution

language:Swift

Solution one:

func isValidSerialization(_ preorder: String) -> Bool {
    let n = preorder.count
    var i = 0
    var stack: [Int] = [1]
    
    while i < n {
    	// 槽位数量不足
        if stack.isEmpty {
            return false
        }
        
        // 取一个字符
        let sIndex = preorder.startIndex
        var index = preorder.index(sIndex, offsetBy: i)
        let c = preorder[index]
        
        // 判断字符
        if c == "," {
            i += 1
        }else if c == "#" {
        	// 空节点
            let last = stack.last! - 1
            if last == 0 {
                stack.removeLast()
            }else{
                stack[stack.count-1] = last
            }
            i += 1
        }else{
            // 读一个数字
            var s = Character("c")
            while i < n && s != "," {
                index = preorder.index(sIndex, offsetBy: i)
                s = preorder[index]
                i += 1
            }
            
            let last = stack.last! - 1
            if last == 0 {
                stack.removeLast()
            }else{
                stack[stack.count-1] = last
            }
            stack.append(2)
        }
    }
    return stack.isEmpty
}

Solution two:

func isValidSerializationV2(_ preorder: String) -> Bool {
    let n = preorder.count
    var i = 0
    var slots = 1
    
    while i < n {
        if slots == 0 {
            return false
        }
        
        let sIndex = preorder.startIndex
        var index = preorder.index(sIndex, offsetBy: i)
        let c = preorder[index]
        
        if c == "," {
            i += 1
        }else if c == "#" {
            slots -= 1
            i += 1
        }else{
            // 读一个数字
            var s = Character("c")
            while i < n && s != "," {
                index = preorder.index(sIndex, offsetBy: i)
                s = preorder[index]
                i += 1
            }
            slots += 1 // slots = slots - 1 + 2
        }
    }
    return slots == 0
}


small note application

Please add image description


Guess you like

Origin blog.csdn.net/xjh093/article/details/123130354