1.递归
class Solution {
public:
vector<int> vc;
vector<int> preorderTraversal(TreeNode* root) {
vc.clear();
if(root == nullptr) return vc;
dfs(root);
return vc;
}
void dfs(TreeNode* root){
if(root == nullptr) return;
vc.push_back(root->val);
dfs(root->left);
dfs(root->right);
}
};
2.迭代
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> vc;
if(root == nullptr) return vc;
stack<TreeNode* > sta;
sta.push(root);
while(!sta.empty()){
TreeNode* node = sta.top();
sta.pop();
// if(node == nullptr) continue;
vc.push_back(node->val);
if(node->right != nullptr) sta.push(node->right);
if(node->left != nullptr) sta.push(node->left);
}
return vc;
}
};
1.递归
class Solution {
public:
vector<int> vc;
vector<int> inorderTraversal(TreeNode* root) {
if(root == nullptr) return vc;
dfs(root);
return vc;
}
void dfs(TreeNode* root){
if(root == nullptr) return;
dfs(root -> left);
vc.push_back(root->val);
dfs(root -> right);
}
};
2.迭代
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> vc;
if(root == nullptr) return vc;
stack<TreeNode* > sta;
// sta.push(root);
while(root || !sta.empty()){
while(root){
sta.push(root);
root = root -> left;
}
root = sta.top();
sta.pop();
vc.push_back(root->val);
root = root->right;
}
return vc;
}
};
1.递归
class Solution {
public:
vector<int> vc;
vector<int> postorderTraversal(TreeNode* root) {
vc.clear();
if(!root) return vc;
dfs(root);
return vc;
}
void dfs(TreeNode* root){
if(!root) return ;
dfs(root->left);
dfs(root->right);
vc.push_back(root->val);
}
};
2.迭代
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> vc;
if(!root) return vc;
stack<TreeNode* > sta;
TreeNode* last;
while(root || !sta.empty()){
while(root){
sta.push(root);
root = root->left;
}
root = sta.top();
if(root->right == nullptr || root->right == last){
sta.pop();
last = root;
vc.push_back(root->val);
root = nullptr;
}else {
root = root->right;
}
}
return vc;
}
};
难度中等1230
给你二叉树的根节点 root
,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> vc;
if(!root) return vc;
queue<TreeNode*> ac;
vc.clear();
ac.push(root);
while(!ac.empty()){
int n = ac.size();
vector<int> x;
for(int i = 0; i < n; i++){
auto b = ac.front();
x.push_back(b->val);
ac.pop();
if(b->left) ac.push(b->left);
if(b->right) ac.push(b->right);
}
vc.push_back(x);
}
return vc;
}
};