前序遍历
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() :val(0), left(nullptr), right(nullptr) {};
TreeNode(int x, TreeNode* left, TreeNode* right) :val(x), left(left), right(right) {};
};
class Solution {
public:
void preorder(TreeNode* root, vector<int>& res) {
if (root == nullptr) {
return;
}
res.push_back(root->val);
preorder(root->left, res);
preorder(root->right, res);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(root, res);
return res;
}
};
中序遍历
int ans1;
int ans2;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() :val(0), left(nullptr), right(nullptr) {};
TreeNode(int x, TreeNode* left, TreeNode* right) :val(x), left(left), right(right) {};
};
class Solution {
public:
void inorder(TreeNode* root, vector<int>& res) {
if (!root) {
ans2 = max(ans2, ans1);
return;
}
ans1 += 1;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right,res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
ans2 = 0;
ans1 = 0;
inorder(root, res);
return res;
}
};
后序遍历
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() :val(0), left(nullptr), right(nullptr) {};
TreeNode(int x, TreeNode* left, TreeNode* right) :val(x), left(left), right(right) {};
};
class Solution {
public:
void preorder(TreeNode* root, vector<int>& res) {
if (root == nullptr) {
return;
}
preorder(root->left, res);
preorder(root->right, res);
res.push_back(root->val);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(root, res);
return res;
}
};
|