树的遍历
作者:
Change01
,
2024-03-24 01:25:59
,
所有人可见
,
阅读 5
前序遍历
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
vector<int> res;
void dfs(TreeNode* Node){
if(Node == nullptr) return;
res.push_back(Node->val);
dfs(Node->left);
dfs(Node->right);
}
vector<int> preorderTraversal(TreeNode* root) {
// write code here
dfs(root);
return res;
}
};
中序遍历
class Solution {
public:
vector<int> res;
void dfs(TreeNode* Node){
if(Node == nullptr) return;
dfs(Node->left);
res.push_back(Node->val);
dfs(Node->right);
}
vector<int> preorderTraversal(TreeNode* root) {
// write code here
dfs(root);
return res;
}
};
后序遍历
class Solution {
public:
vector<int> res;
void dfs(TreeNode* Node){
if(Node == nullptr) return;
dfs(Node->left);
dfs(Node->right);
res.push_back(Node->val);
}
vector<int> preorderTraversal(TreeNode* root) {
// write code here
dfs(root);
return res;
}
};