递归:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
preorder(root, res);
return res;
}
void preorder(TreeNode* root, vector<int> &res) {
if(!root) return;
res.push_back(root->val);
if(root->left) preorder(root->left, res);
if(root->right) preorder(root->right, res);
}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
inorder(root, res);
return res;
}
void inorder(TreeNode* root, vector<int>& res) {
if(!root) return;
if(root->left) inorder(root->left, res);
res.push_back(root->val);
if(root->right) inorder(root->right, res);
}
};
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
postorder(root, res);
return res;
}
void postorder(TreeNode* root, vector<int> &res) {
if(!root) return;
if(root->left) postorder(root->left, res);
if(root->right) postorder(root->right, res);
res.push_back(root->val);
}
};
迭代:
先序
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> s;
s.push(root);
TreeNode* tmp;
while(!s.empty()) {
tmp = s.top();
s.pop();
res.push_back(tmp->val);
if(tmp->right) s.push(tmp->right);
if(tmp->left) s.push(tmp->left);
}
return res;
}
};
中序:
自己写的,但是内存超限,不清楚哪里有问题 (可能是重复访问,压栈过多)
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> s;
s.push(root);
TreeNode* tmp;
while(!s.empty()) {
tmp = s.top();
while(tmp->left) {
s.push(tmp);
tmp = tmp->left;
}
res.push_back(tmp->val);
s.pop();
if(tmp->right) s.push(tmp->right);
}
return res;
}
参考别人的模板写的: 常用算法及参考实现
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> s;
TreeNode* tmp = root;
while(!s.empty() || tmp) {
while(tmp) {
s.push(tmp);
tmp = tmp->left;
}
tmp = s.top();
s.pop();
res.push_back(tmp->val);
//if(tmp->right) s.push(tmp->right);
tmp = tmp->right;
}
return res;
}
后序:(比较复杂,有几个点需要注意的)
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> path;
unordered_set<TreeNode*> _set;
TreeNode* node;
if(root) path.push(root);
while(!path.empty()) {
node = path.top(); //只取出元素,不弹栈:只有访问过的节点才被弹出
bool leftVisited = true, rightVisited = true;
if(node->right && _set.find(node->right) == _set.end()) {
rightVisited = false;
path.push(node->right);
}
if(node->left && _set.find(node->left) == _set.end()) {
leftVisited = false;
path.push(node->left);
}
if(leftVisited && rightVisited) {
res.push_back(node->val);
path.pop();
_set.insert(node);
}
}
return res;
}
};