/**
* 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 {
TreeNode *findMax(TreeNode *root) {
TreeNode *cur = root;
while (cur && cur->right) {
cur = cur->right;
}
return cur;
}
public:
TreeNode *deleteNode(TreeNode *root, int key) {
if (root == nullptr) {
return root;
}
if (key < root->val) {
root->left = deleteNode(root->left, key);
return root;
} else if (key > root->val) {
root->right = deleteNode(root->right, key);
return root;
}
if (root->left == nullptr) {
return root->right;
} else if (root->right == nullptr) {
return root->left;
}
TreeNode *target = findMax(root->left);
root->val = target->val;
root->left = deleteNode(root->left, target->val);
return root;
}
};
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
int n = matrix.size() * matrix[0].size();
ans.reserve(n);
int upper_bound = 0, lower_bound = matrix.size() - 1;
int left_bound = 0, right_bound = matrix[0].size() - 1;
while (true) {
for (int i = left_bound; i <= right_bound; ++i) {
ans.push_back(matrix[upper_bound][i]);
}
if (++upper_bound > lower_bound) break;
for (int i = upper_bound; i <= lower_bound; ++i) {
ans.push_back(matrix[i][right_bound]);
}
if (--right_bound < left_bound) break;
for (int i = right_bound; i >= left_bound; --i) {
ans.push_back(matrix[lower_bound][i]);
}
if (--lower_bound < upper_bound) break;
for (int i = lower_bound; i >= upper_bound; --i) {
ans.push_back(matrix[i][left_bound]);
}
if (++left_bound > right_bound) break;
}
return ans;
}
};