前序递归遍历:
class Solution {
public:
void traversal(TreeNode* root, vector<int>& vec) {
if(root == NULL) return;
vec.push_back(root->val);
traversal(root->left, vec);
traversal(root->right, vec);
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> vec;
traversal(root, vec);
return vec;
}
};
中序递归遍历:
class Solution {
public:
void traversal(TreeNode* root, vector<int>& vec) {
if(root == NULL) return;
traversal(root->left, vec);
vec.push_back(root->val);
traversal(root->right, vec);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> vec;
traversal(root, vec);
return vec;
}
};
后序递归遍历:
class Solution {
public:
void traversal(TreeNode* root, vector<int>& vec) {
if(root == NULL) return;
traversal(root->left, vec);
traversal(root->right, vec);
vec.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode* root) {
vector<int> vec;
traversal(root, vec);
return vec;
}
};
前序非递归遍历:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode *> sta;
vector<int> vec;
if(root == NULL) return vec;
sta.push(root);
while(!sta.empty()) {
TreeNode* tem = sta.top();
sta.pop();
vec.push_back(tem->val);
if(tem->right != NULL) sta.push(tem->right);
if(tem->left != NULL) sta.push(tem->left);
}
return vec;
}
};
中序非递归遍历:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> sta;
vector<int> vec;
if(root == NULL) return vec;
TreeNode* cur = root;
while(cur != NULL || !sta.empty()) {
while(cur != NULL) {
sta.push(cur);
cur = cur->left;
}
cur = sta.top();
sta.pop();
vec.push_back(cur->val);
cur = cur->right;
}
return vec;
}
};
后序非递归遍历:
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> sta;
vector<int> vec;
if(root == NULL) return vec;
sta.push(root);
while(!sta.empty()) {
TreeNode* cur = sta.top();
sta.pop();
vec.push_back(cur->val);
if(cur->left) sta.push(cur->left);
if(cur->right) sta.push(cur->right);
}
reverse(vec.begin(), vec.end());
return vec;
}
};
统一迭代法:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> sta;
vector<int> vec;
if(root == NULL) return vec;
sta.push(root);
while(!sta.empty()) {
TreeNode* tem = sta.top();
sta.pop();
if(tem != NULL) {
if(tem->right) sta.push(tem->right);
sta.push(tem);
sta.push(NULL);
if(tem->left) sta.push(tem->left);
}else {
tem = sta.top();
sta.pop();
vec.push_back(tem->val);
}
}
return vec;
}
};
层序遍历:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
vector<vector<int>> res;
if(root == NULL) return res;
que.push(root);
while(!que.empty()) {
int size = que.size();
vector<int> vec;
for(int i = 0; i < size; i++) {
TreeNode* tem = que.front();
que.pop();
vec.push_back(tem->val);
if(tem->left) que.push(tem->left);
if(tem->right) que.push(tem->right);
}
res.push_back(vec);
}
return res;
}
};