节点信息
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) :val(0), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
二叉树前中后序遍历递归版本
前序遍历
void preOrder(vector<int> &res, TreeNode *root) {
if (root == nullptr) return;
res.push_back(root->val);
preOrder(res, root->left);
preOrder(res, root->right);
}
中序遍历
void inOrder(vector<int> &res, TreeNode *root) {
if (root == nullptr) return;
inOrder(res, root->left);
res.push_back(root->val);
inOrder(res, root->right);
}
后序遍历
void postOrder(vector<int> &res, TreeNode *root) {
if (root == nullptr) return;
postOrder(res, root->left);
postOrder(res, root->right);
res.push_back(root->val);
}
二叉树前中后序遍历非递归版本
前序遍历
void preOrder(vector<int> &res, TreeNode *root) {
if (root == nullptr) return;
stack<TreeNode *> s;
TreeNode *cur = root;
s.push(cur);
while (!s.empty()) {
cur = s.top();
s.pop;
res.push_back(cur->val);
if (cur->right) s.push(cur->right);
if (cur->left) s.push(cur->left);
}
}
中序遍历
void inOrder(vector<int> &res, TreeNode *root) {
if (root == nullptr) return;
stack<TreeNode *> s;
TreeNode *cur = root;
while (!s.empty() || cur != nullptr) {
while (cur != nullptr) {
s.push(cur);
cur = cur->left;
}
TreeNode *tmp = s.top();
s.pop();
res.push_back(tmp->val);
if (tmp->right) cur = tmp->right;
}
}
后序遍历
先按照“根右左”遍历,最后在翻转成“左右根”
void postOrder(vector<int> &res, TreeNode *root) {
if (root == nullptr) return;
stack<TreeNode *> s;
TreeNode *cur = root;
s.push(cur);
while (!s.empty()) {
cur = s.top();
s.pop();
res.push_back(cur->val);
if (cur->left) s.push(cur->left);
if (cur->right) s.push(cur->right);
}
reverse(res.begin(), res.end());
}
二叉树层次遍历
//层次遍历
vector<vector<int>> levelOrder( TreeNode *root) {
vector<vector<int>> res;
if (root == nullptr) return res;
queue<pair<TreeNode *, int>> q;
TreeNode *cur = root;
q.push(make_pair(cur, 0));
while (!q.empty()) {
pair<TreeNode *, int> tmp = q.front();
q.pop();
TreeNode *node = tmp.first;
int level = tmp.second;
if (level == res.size()) res.push_back(vector<int> ());
res[level].push_back(node->val);
if (node->left) q.push(make_pair(node->left, level + 1));
if (node->right) q.push(make_pair(node->right, level + 1));
}
return res;
}