二叉树前序遍历:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> res;
vector<int> preorderTraversal(TreeNode* root) {
if(root!=NULL){
res.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
return res;
}
};
二叉树中序遍历:
class Solution {
public:
vector<int> res;
vector<int> inorderTraversal(TreeNode* root) {
if(root!=NULL){
inorderTraversal(root->left);
res.push_back(root->val);
inorderTraversal(root->right);
}
return res;
}
};
后序遍历:
class Solution {
public:
vector<int> res;
vector<int> postorderTraversal(TreeNode* root) {
if(root!=NULL){
postorderTraversal(root->left);
postorderTraversal(root->right);
res.push_back(root->val);
}
return res;
}
};
层次遍历:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> m;
vector<vector<int>> res;
if(root==NULL){
return res;
}
m.push(root);
while(!m.empty()){
vector<int> temp;
int size = m.size();
while(size--){
TreeNode* t = m.front();
temp.push_back(t->val);
m.pop();
if(t->left){
m.push(t->left);
}
if(t->right){
m.push(t->right);
}
}
res.push_back(temp);
}
return res;
}
};