递归法
先序
void preorderTravesal(TreeNode* root, vector<int>& vec) {
if (!root) return;
vec.push_back(root->val);
preorderTravesal(root->left, vec);
preorderTravesal(root->right, vec);
}
中序
void inorderTravesal(TreeNode* root, vector<int>& vec) {
if (!root) return;
inorderTravesal(root->left, vec);
vec.push_back(root->val);
inorderTravesal(root->right, vec);
}
后序
void postderTravesal(TreeNode* root, vector<int>& vec) {
if (!root) return;
inorderTravesal(root->left, vec);
inorderTravesal(root->right, vec);
vec.push_back(root->val);
}
迭代法
前序
vector<int> preorderTravesal(TreeNode* root) {
vector<int> ans;
if (!root) return ans;
stack<TreeNode*> stk;
stk.push(root);
while (!stk.empty()) {
TreeNode* node = stk.top();
stk.pop();
ans.push_back(node->val);
if (node->right) stk.push(node->right);
if (node->left) stk.push(node->left);
}
return ans;
}
中序
vector<int> inorderTravesal(TreeNode* root) {
vector<int> ans;
stack<TreeNode*> stk;
TreeNode* cur = root;
while (!stk.empty() || cur) {
if (cur) {
stk.push(cur);
cur = cur->left;
} else {
cur = stk.top();
stk.pop();
ans.push_back(cur->val);
cur = cur->right;
}
}
return ans;
}
后序
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> stk;
vector<int> ans;
if (!root) return ans;
stk.push(root);
while (!stk.empty()) {
TreeNode* node = stk.top();
stk.pop();
ans.push_back(node->val);
if (node->left) stk.push(node->left);
if (node->right) stk.push(node->right);
}
reverse(ans.begin(), ans.end());
return ans;
}
};
层序遍历
vector<int> levelOrder(TreeNode* root) {
vector<int> ans;
if (!root) return ans;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()) {
int size = que.size();
for(int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
ans.push_back(node->val);
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return ans;
}