题解 | #二叉树遍历#
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
#include<iostream> using namespace std; struct TreeNode{ char data; TreeNode* left; TreeNode* right; }; string str; int pos = 0;//当前遍历到str的哪个节点 //根据先序建立二叉树 //当树构建完成时,返回树的根节点 TreeNode* BuildTree(){ char c = str[pos++];//pos++不能忘 if(c == '#'){ return NULL; }else{ TreeNode* root = new TreeNode; root->data = c; root->left = BuildTree(); root->right = BuildTree(); return root;//此子树建立完成,返回根节点 } } void InOrder(TreeNode* root){ if(root == NULL) return; else{ InOrder(root->left); cout<<root->data<<" "; InOrder(root->right); } } int main(){ while(getline(cin,str)){ TreeNode* root = BuildTree(); InOrder(root); cout<<endl; } return 0; }
王道考研机试 文章被收录于专栏
包含考研机试打卡表题目