NC45 实现二叉树先序,中序和后序遍历
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362?tpId=196&tqId=37153&rp=1&ru=/exam/oj&qru=/exam/oj&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26pageSize%3D50%26search%3D%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D196&difficulty=undefined&judgeStatus=undefined&tags=581&title=
class Solution {
public:
//创建三个容器用于存前序、中序、后序遍历的结果
vector<int>pre;
vector<int>mid;
vector<int>post;
vector<vector<int> > threeOrders(TreeNode* root) {
//只要根节点存在,就求这棵树的前序、中序、后序
if(root!=nullptr){
preorder(root);
midorder(root);
postorder(root);
}
//用一个二维的vector用来存前中后序的结果
vector<vector<int>> res{pre,mid,post};
return res;
}
//先序遍历
void preorder(TreeNode* root){
//如果没有节点了,就直接结束
if(root==nullptr){
return;
}
//否则,先序遍历:根左右(将根放入容器中)(递归遍历)
pre.push_back(root->val);
preorder(root->left);
preorder(root->right);
}
void midorder(TreeNode* root){
//没有节点,结束
if(root==nullptr){
return;
}
//中序遍历:左根右(递归)(根入容器)
midorder(root->left);
mid.push_back(root->val);
midorder(root->right);
}
void postorder(TreeNode* root){
//没有节点,结束
if(root==nullptr){
return;
}
//后序遍历:左右根(递归)(根入容器)
postorder(root->left);
postorder(root->right);
post.push_back(root->val);
}
};