二叉树的种类:满二叉树、完全二叉树、二叉搜索树、平衡二叉搜索树。
递归算法:
确定三要素:参数返回值,终止条件,单层递归逻辑。
// 前序遍历
class Solution {
public:
void traversal(TreeNode* cur, vector<int> &vec) {
if (cur == nullptr) return;
vec.push_back(cur->val);
traversal(cur->left, vec);
traversal(cur->right, vec);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root, result);
return result;
}
};
前中后的区别就在于vec.push_back(cur->val);这一行的位置。
迭代法:
// 前序
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> res;
if (root == nullptr) return res;
st.push(root);
TreeNode* node;
while (!st.empty()) {
node = st.top();
st.pop();
res.push_back(node->val);
if (node->right) st.push(node->right);
if (node->left) st.push(node->left);
}
return res;
}
};
// 后序
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> res;
if (root == nullptr) return res;
st.push(root);
TreeNode* node;
while (!st.empty()) {
node = st.top();
st.pop();
res.push_back(node->val);
if (node->left) st.push(node->left);
if (node->right) st.push(node->right);
}
reverse(res.begin(), res.end());
return res;
}
};
// 中序
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
TreeNode* cur = root;
while (cur != nullptr || !st.empty()) {
if (cur != nullptr) {
st.push(cur);
cur = cur->left;
}else {
cur = st.top();
st.pop();
res.push_back(cur->val);
cur = cur->right;
}
}
return res;
}
};
中左右->左右中只需将左右对调然后reverse结果就可以。
// 统一迭代法
// 中序
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if (root != nullptr) st.push(root);
while (!st.empty()) {
TreeNode* cur = st.top();
if (cur != nullptr) {
st.pop();
if (cur->right) st.push(cur->right);
st.push(cur);
st.push(nullptr);
if (cur->left) st.push(cur->left);
}else {
st.pop();
res.push_back(st.top()->val);
st.pop();
}
}
return res;
}
};
// 前序
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if (root != nullptr) st.push(root);
while (!st.empty()) {
TreeNode* cur = st.top();
if (cur != nullptr) {
st.pop();
if (cur->right) st.push(cur->right);
if (cur->left) st.push(cur->left);
st.push(cur);
st.push(nullptr);
}else {
st.pop();
res.push_back(st.top()->val);
st.pop();
}
}
return res;
}
};
// 后序
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
if (root != nullptr) st.push(root);
while (!st.empty()) {
TreeNode* cur = st.top();
if (cur != nullptr) {
st.pop();
st.push(cur);
st.push(nullptr);
if (cur->right) st.push(cur->right);
if (cur->left) st.push(cur->left);
}else {
st.pop();
res.push_back(st.top()->val);
st.pop();
}
}
return res;
}
};