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
2
3
4
5
6
7
8
9
10
11
12
Example 1:

Input: preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
Output: true
Example 2:

Input: preorder = "1,#"
Output: false
Example 3:

Input: preorder = "9,#,#,1"
Output: false

思路

本题有两种写法,我用了最笨的一种,每遇到两个#,将这两个 hash 和对应的 leaf node 删掉,然后添加一个#,要注意的是需要使用 while 循环,因为可能会在添加#之后形成新的满足 pop 要求的组合。要注意的是不能直接用 index 访问,因为可能会出现两位数字(92)。
另一种写法是聪明很多,因为 external node 数量必然比 internal 多 1,每遇到一个 val,counter++,遇到#,counter–,如果读完所有的 node 时,count 为-1,则有效(如果未读完所有 node,count 就为 1,意味着此时已经无法插入 node,则此 tree 无效)。
截屏2022-05-18 下午8.44.49

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidSerialization(string preorder) {
//if it's #
if(preorder[0] == '#' && preorder.size() == 1)
return true;
else if(preorder[0] == '#' && preorder.size() != 1)
return false;
preorder += ',';
stringstream str(preorder);
string ele;
getline(str, ele, ',');
vector<string> stack;
stack.push_back(ele);
while(getline(str, ele, ',')){
stack.push_back(ele);
if(stack.back() == "#"){
while(stack.size() > 2 && stack.back() == "#" && stack[stack.size() - 2] == "#" && stack[stack.size() - 3] != "#" ){
stack.pop_back();
stack.pop_back();
stack.pop_back();
stack.push_back("#");
}
}
}
if(stack.size() == 1 && stack.back() == "#")
return true;
return false;
}
};

bool isValidSerialization(string p)
{
stringstream ss{p};
int c{0};
for( ; c!=-1 and !ss.eof(); getline(ss, p, ','))
p[0]=='#' ? --c : ++c;
return c==-1 and ss.eof();
}
  1. 5 月 14 日 每日一题
    1. 105. Construct Binary Tree from Preorder and Inorder Traversal
    2. 思路
    3. 代码