One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #.node
_9_ / \ 3 2 / \ / \ 4 1 # 6 / \ / \ / \ # # # # # #
For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where # represents a null node.git
Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.github
Each comma separated value in the string must be either an integer or a character '#' representing null pointer.算法
You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3".app
Example 1:ui
Input: "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output: true
Example 2:指針
Input: "1,#"
Output: false
Example 3:code
Input: "9,#,#,1"
Output: falseorm
序列化二叉樹的一種方法是使用前序遍歷。當咱們遇到一個非空節點時,咱們能夠記錄下這個節點的值。若是它是一個空節點,咱們能夠使用一個標記值記錄,例如 #。ip
_9_ / \ 3 2 / \ / \ 4 1 # 6 / \ / \ / \ # # # # # #
例如,上面的二叉樹能夠被序列化爲字符串 "9,3,4,#,#,1,#,#,2,#,6,#,#",其中 # 表明一個空節點。
給定一串以逗號分隔的序列,驗證它是不是正確的二叉樹的前序序列化。編寫一個在不重構樹的條件下的可行算法。
每一個以逗號分隔的字符或爲一個整數或爲一個表示 null 指針的 '#' 。
你能夠認爲輸入格式老是有效的,例如它永遠不會包含兩個連續的逗號,好比 "1,,3" 。
示例 1:
輸入: "9,3,4,#,#,1,#,#,2,#,6,#,#"
輸出: true
示例 2:
輸入: "1,#"
輸出: false
示例 3:
輸入: "9,#,#,1"
輸出: false
# -*- coding: utf-8 -*- # @Author: 何睿 # @Create Date: 2019-03-17 09:44:27 # @Last Modified by: 何睿 # @Last Modified time: 2019-03-17 10:03:55 class Solution: def isValidSerialization(self, preorder: str) -> bool: # stack:用於記錄遍歷到的節點值 # count:stack 中剩餘的節點個數 stack, count = [], 0 for item in preorder.split(","): stack.append(item) count += 1 # 若是 stack 中末位兩個元素是 #,說明這兩個節點前面是一個葉子節點 # 將兩個 # 彈出 ,將葉子節點置爲 None,即 # # 若是是前序遍歷,那麼 stack 最後必定會剩下一個 # while count > 1 and stack[-1] == "#" and stack[-2] == "#": stack.pop() stack.pop() if not stack: return False stack[-1] = "#" count -= 2 # 當且僅當 stack 中只剩下一個元素且爲 # 時返回 True. return True if len(stack) == 1 and stack[0] == "#" else False