前序遍历
根-左-右,递归
class Solution{
public:
vector<int> preorderTraversal(TreeNode* root)
{
vector<int> result;
preorder(root, result);
return result;
}
void preorder(TreeNode* cur, vector<int> &res)
{
if(cur == nullptr) return;
res.push_back(cur->val);
preorder(cur->left, res);
preorder(cur->right, res);
}
};
中序遍历
左-根-右
class Sulution{
public{
vector<int> inorderTranserval(TreeNode* root)
{
verctor<int> result;
inorder(root, result);
return result;
}
void inorder(TreeNode* cur, vector<int> &res)
{
if(cur == nullptr){return;}
inorder(cur->left, res);
res.push_back(cur->val);
inorder(cur->right,res);
}
}
};
后序遍历
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
postorder(root, result);
return result;
}
void postorder(TreeNode* cur, vector<int> &res){
if(cur == nullptr){
return;
}
postorder(cur->left, res);
postorder(cur->right, res);
res.push_back(cur->val);
}
};
层序遍历
入队根节点,出队根节点,入队他的左子树和右子树,出队左子树,入队左子树的左子树和右子树。。。以此类推。
class solution
{
public:
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> res;
if(root == nullptr){return res;}
queue<TreeNode*> q;
q.push(root);
while(!q.empty)
{
vector<int> vec;
int qSize = q.size();
for(int i = 0; i<qSize; ++i)
{
TreeNode* node = q.front();
q.pop();
vec.push_back(node->val);
if(node->left)q.push(node->left);
if(node->right)q.push(node->right);
}
res.push_bac(vec);
}
return res;
}
};
层序遍历Ⅱ
给你二叉树的根节点 root
,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
与层序遍历相同,只是在输出前反转一下即可。
reverse(res.begin(),res.end());