欢迎大家来到IT世界,在知识的湖畔探索吧!
- 前序遍历(中左右):5 4 1 2 6 7 8
- 中序遍历(左中右):1 4 2 5 7 6 8
- 后序遍历(左右中):1 2 4 7 8 6 5
- 层序遍历:5 4 6 1 2 7 8
1、前序遍历
class Solution {public: void dfs(TreeNode *cur, vector<int> &vec) { if (cur == NULL) return; vec.push_back(cur->val); // 中 dfs(cur->left, vec); // 左 dfs(cur->right, vec); // 右 } vector<int> preorderTraversal(TreeNode *root) { vector<int> res; dfs(root, res); return res; }};
欢迎大家来到IT世界,在知识的湖畔探索吧!
2、中序遍历
欢迎大家来到IT世界,在知识的湖畔探索吧!class Solution {
public:
void dfs(TreeNode *cur, vector<int> &vec) {
if (cur == NULL) return;
dfs(cur->left, vec);
vec.push_back(cur->val);
dfs(cur->right, vec);
}
vector<int> inorderTraversal(TreeNode *root) {
vector<int> res;
dfs(root, res);
return res;
}
};
3、后序遍历
class Solution {
public:
void dfs(TreeNode *cur, vector<int> &vec) {
if (cur == NULL) return;
dfs(cur->left, vec);
dfs(cur->right, vec);
vec.push_back(cur->val);
}
vector<int> postorderTraversal(TreeNode *root) {
vector<int> res;
dfs(root, res);
return res;
}
};
4、层序遍历
每一层放入一个 vector 写法,如:[[3],[9,20],[15,7]]
欢迎大家来到IT世界,在知识的湖畔探索吧!class Solution {
public:
vector<vector<int>> levelOrder(TreeNode *root) {
vector<vector<int>> res;
if (!root) return res;
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
int layerSz = q.size();
vector<int> layer;
for (int i = 0; i < layerSz; i++) {
auto node = q.front();
q.pop();
layer.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
res.push_back(layer);
}
return res;
}
};
全部放一起,如:[3 9 20 15 7 ]
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode *root) {
vector<int> res;
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
auto node = q.front();
q.pop();
res.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
for (const auto &c : res) cout << c << " ";
return res;
}
};
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/30221.html