LeetCode Daily Question 30
5 月 14 日 每日一题
105. Construct Binary Tree from Preorder and Inorder Traversal
One way to serialize a binary tree is to use preorder 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 ‘#’.
For example, the above binary tree can be serialized to the string “9,3,4,#,#,1,#,#,2,#,6,#,#”, where ‘#’ represents a null node.
Given a string of comma-separated values preorder, return true if it is a correct preorder traversal serialization of a binary tree.
It is guaranteed that 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”.
Note: You are not allowed to reconstruct the tree.
1 | Example 1: |
思路
本题有两种写法,我用了最笨的一种,每遇到两个#,将这两个 hash 和对应的 leaf node 删掉,然后添加一个#,要注意的是需要使用 while 循环,因为可能会在添加#之后形成新的满足 pop 要求的组合。要注意的是不能直接用 index 访问,因为可能会出现两位数字(92)。
另一种写法是聪明很多,因为 external node 数量必然比 internal 多 1,每遇到一个 val,counter++,遇到#,counter–,如果读完所有的 node 时,count 为-1,则有效(如果未读完所有 node,count 就为 1,意味着此时已经无法插入 node,则此 tree 无效)。
代码
1 | /** |