Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: update solutions to lc/lcof2 problems #2882

Merged
merged 1 commit into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions lcof/面试题18. 删除链表的节点/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,15 +256,15 @@ class Solution {
func deleteNode(_ head: ListNode?, _ val: Int) -> ListNode? {
let dummy = ListNode(0, head)
var current: ListNode? = dummy

while current?.next != nil {
if current?.next?.val == val {
current?.next = current?.next?.next
break
}
current = current?.next
}

return dummy.next
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ class Solution {
func exchange(_ nums: [Int]) -> [Int] {
var nums = nums
var j = 0

for i in 0..<nums.count {
if nums[i] % 2 == 1 {
let temp = nums[i]
Expand All @@ -198,7 +198,7 @@ class Solution {
j += 1
}
}

return nums
}
}
Expand Down
313 changes: 69 additions & 244 deletions lcof/面试题37. 序列化二叉树/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,20 +339,23 @@ func (this *Codec) deserialize(data string) *TreeNode {
* @return {string}
*/
var serialize = function (root) {
if (!root) return '[]';
let queue = [root];
let res = '';
while (queue.length) {
let node = queue.shift();
if (node) {
res += node.val + ',';
queue.push(node.left);
queue.push(node.right);
if (root === null) {
return null;
}
const ans = [];
const q = [root];
let index = 0;
while (index < q.length) {
const node = q[index++];
if (node !== null) {
ans.push(node.val.toString());
q.push(node.left);
q.push(node.right);
} else {
res += 'null' + ',';
ans.push('#');
}
}
return `[${res.substring(0, res.length - 1)}]`;
return ans.join(',');
};

/**
Expand All @@ -362,22 +365,26 @@ var serialize = function (root) {
* @return {TreeNode}
*/
var deserialize = function (data) {
if (!data || data.length <= 2) return null;
let arr = data.substring(1, data.length - 1).split(',');
let root = new TreeNode(arr.shift());
let queue = [root];
while (queue.length) {
let node = queue.shift();
let leftVal = arr.shift();
if (leftVal !== 'null') {
node.left = new TreeNode(leftVal);
queue.push(node.left);
if (data === null) {
return null;
}
const vals = data.split(',');
let i = 0;
const root = new TreeNode(parseInt(vals[i++]));
const q = [root];
let index = 0;
while (index < q.length) {
const node = q[index++];
if (vals[i] !== '#') {
node.left = new TreeNode(+vals[i]);
q.push(node.left);
}
let rightVal = arr.shift();
if (rightVal !== 'null') {
node.right = new TreeNode(rightVal);
queue.push(node.right);
i++;
if (vals[i] !== '#') {
node.right = new TreeNode(+vals[i]);
q.push(node.right);
}
i++;
}
return root;
};
Expand All @@ -401,239 +408,57 @@ var deserialize = function (data) {
* }
*/
public class Codec {
public string serialize(TreeNode root) {
return rserialize(root, "");
}

public TreeNode deserialize(string data) {
string[] dataArray = data.Split(",");
LinkedList<string> dataList = new LinkedList<string>(dataArray.ToList());
return rdeserialize(dataList);
}

public string rserialize(TreeNode root, string str) {
// Encodes a tree to a single string.
public string serialize(TreeNode root) {
if (root == null) {
str += "None,";
} else {
str += root.val.ToString() + ",";
str = rserialize(root.left, str);
str = rserialize(root.right, str);
}
return str;
}

public TreeNode rdeserialize(LinkedList<string> dataList) {
if (dataList.First.Value.Equals("None")) {
dataList.RemoveFirst();
return null;
}

TreeNode root = new TreeNode(int.Parse(dataList.First.Value));
dataList.RemoveFirst();
root.left = rdeserialize(dataList);
root.right = rdeserialize(dataList);

return root;
}
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
```

<!-- tabs:end -->

<!-- solution:end -->

<!-- solution:start-->

### 方法二:前序遍历

当二叉树的前中后序列不包含叶子节点时需要前中、前后、中后三种组合方式之一才能确定一颗二叉树,但当前序和后序遍历序列中包含叶子节点时,可以仅通过前序或后序遍历序列构建一颗二叉树。

在前序遍历序列化时,我们以任意特殊字符表示叶子节点,返回序列化后的字符串;反序列化时对序列化字符串根据分隔符进行切分后使用列表的第一个元素作为二叉树的根节点,然后利用列表的其他元素递归生成左右子树即可。

时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。

<!-- tabs:start -->

#### C++

```cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
string empty = "#";
string sep = ",";
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root) return empty + sep;
string res = to_string(root->val) + sep;
res += serialize(root->left);
res += serialize(root->right);
return res;
}

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
list<string> nodes;
size_t pos = 0;
string node;
while ((pos = data.find(sep)) != string::npos) {
node = data.substr(0, pos);
nodes.push_back(node);
data.erase(0, pos + sep.length());
List<string> ans = new List<string>();
Queue<TreeNode> q = new Queue<TreeNode>();
q.Enqueue(root);
while (q.Count > 0) {
TreeNode node = q.Dequeue();
if (node != null) {
ans.Add(node.val.ToString());
q.Enqueue(node.left);
q.Enqueue(node.right);
} else {
ans.Add("#");
}
}
return deserialize(nodes);
}

TreeNode* deserialize(list<string>& data) {
if (data.empty()) return nullptr;
string first = data.front();
data.pop_front();
if (first == empty) return nullptr;
TreeNode* root = new TreeNode(stoi(first));
root->left = deserialize(data);
root->right = deserialize(data);
return root;
}
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
```

#### JavaScript

```js
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/

/**
* Encodes a tree to a single string.
*
* @param {TreeNode} root
* @return {string}
*/
var serialize = function (root) {
if (root == null) {
return '#';
return string.Join(",", ans);
}
const { val, left, right } = root;
return `${val},${serialize(left)},${serialize(right)}`;
};

/**
* Decodes your encoded data to tree.
*
* @param {string} data
* @return {TreeNode}
*/
var deserialize = function (data) {
const vals = data.split(',');
let index = 0;
const dfs = () => {
if (vals[index] == '#') {
index++;
// Decodes your encoded data to tree.
public TreeNode deserialize(string data) {
if (data == null) {
return null;
}
const res = new TreeNode(vals[index++]);
res.left = dfs();
res.right = dfs();
return res;
};
return dfs();
};

/**
* Your functions will be called as such:
* deserialize(serialize(root));
*/
```

<!-- tabs:end -->

<!-- solution:end -->

<!-- solution:start-->

### 方法三:后序遍历

在后序遍历序列化时,我们以任意特殊字符表示叶子节点,返回序列化后的字符串;反序列化时对序列化字符串根据分隔符进行切分后使用列表的最后一个元素作为二叉树的根节点,然后利用列表的其他元素递归生成左右子树即可。

时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为二叉树的节点个数。

<!-- tabs:start -->

#### C++

```cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
string empty = "#";
string sep = ",";
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (!root) return empty + sep;
string res = "";
res += serialize(root->left);
res += serialize(root->right);
res += to_string(root->val) + sep;
return res;
}

// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
vector<string> nodes;
size_t pos = 0;
string node;
while ((pos = data.find(sep)) != string::npos) {
node = data.substr(0, pos);
nodes.push_back(node);
data.erase(0, pos + sep.length());
string[] vals = data.Split(',');
int i = 0;
TreeNode root = new TreeNode(int.Parse(vals[i++]));
Queue<TreeNode> q = new Queue<TreeNode>();
q.Enqueue(root);
while (q.Count > 0) {
TreeNode node = q.Dequeue();
if (vals[i] != "#") {
node.left = new TreeNode(int.Parse(vals[i]));
q.Enqueue(node.left);
}
i++;
if (vals[i] != "#") {
node.right = new TreeNode(int.Parse(vals[i]));
q.Enqueue(node.right);
}
i++;
}
return deserialize(nodes);
}

TreeNode* deserialize(vector<string>& nodes) {
if (nodes.empty()) return nullptr;
string front = nodes.back();
nodes.pop_back();
if (front == empty) return nullptr;
TreeNode* root = new TreeNode(stoi(front));
// 先构造右子树,后构造左子树
root->right = deserialize(nodes);
root->left = deserialize(nodes);
return root;
}
};
}

// Your Codec object will be instantiated and called as such:
// Codec codec;
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
```

Expand Down
Loading
Loading