一、递归
1.1 前序遍历
void preprder(TreeNode* root, vector<int> &ans) {
if(root == nullptr) return;
ans.push_back(root -> val);
pre(root -> left, ans);
pre(root -> right, ans);
}
1.2 中序遍历
void inorder(TreeNode* root, vector<int> &ans) {
if(root == nullptr) return;
pre(root -> left, ans);
ans.push_back(root -> val);
pre(root -> right, ans);
}
1.3 后序遍历
void inorder(TreeNode* root, vector<int> &ans) {
if(root == nullptr) return;
pre(root -> left, ans);
pre(root -> right, ans);
ans.push_back(root -> val);
}
二、迭代
2.1 前序遍历
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
if(root == nullptr) return ans;
stack<TreeNode*> stk;
while(!stk.empty() || root != nullptr) {
while(root != nullptr) {
ans.push_back(root->val);
stk.push(root);
root = root -> left;
}
root = stk.top();
stk.pop();
root = root -> right;
}
return ans;
}
2.2 中序遍历
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
if(root == nullptr) return ans;
stack<TreeNode*> stk;
while (root != nullptr || !stk.empty()) {
while (root != nullptr) {
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
ans.push_back(root->val);
root = root->right;
}
return ans;
}
2.3 后序遍历
2.3.1 方法一
vector<int> postorderTraversal(TreeNode *root) {
vector<int> ans;
if (root == nullptr) {
return ans;
}
stack<TreeNode*> stk;
TreeNode *prev = nullptr;
while (root != nullptr || !stk.empty()) {
while (root != nullptr) {
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
if (root->right == nullptr || root->right == prev) {
ans.push_back(root->val);
prev = root;
root = nullptr;
} else {
stk.push(root);
root = root->right;
}
}
return res;
}
2.3.2 方法二
用一个辅助栈记录访问路径。后序遍历,树中每一个节点需要进栈三次,出栈三次,第一次出栈是遍历节点左子树,第二次出栈是遍历节点右子树,第三次出栈是访问节点。
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
if(root == nullptr) return ans;
stack<pair<TreeNode*,int>> stk;
stk.push({root, 0});
while(!stk.empty()) {
pair<TreeNode*,int> p = stk.top();
stk.pop();
if(p.second == 0) {
stk.push({p.first, 1});
if(p.first->left != nullptr) {
stk.push({p.first->left, 0});
}
}
if(p.second == 1) {
stk.push({p.first, 2});
if(p.first->right != nullptr) {
stk.push({p.first->right, 0});
}
}
if(p.second == 2) {
ans.push_back(p.first->val);
}
}
return ans;
}
三、层序遍历
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> ans;
vector<int> tmp;
if(root == nullptr) return ans;
queue<TreeNode*> q;
q.push(root);
tmp.push_back(root->val);
while(!q.empty()) {
ans.push_back(tmp);
int currentSize = q.size();
tmp.clear();
for(int i = 0; i < currentSize; i++) {
TreeNode* p = q.front();
q.pop();
if(p->left != nullptr) {
q.push(p->left);
tmp.push_back(p->left->val);
}
if(p->right != nullptr) {
q.push(p->right);
tmp.push_back(p->right->val);
}
}
}
return ans;
}
|