题解 | #二叉树遍历#

二叉树遍历

http://www.nowcoder.com/questionTerminal/6e732a9632bc4d12b442469aed7fe9ce

#include<iostream>
#include<string>
using namespace std;

struct node{//结点
  char data;
  node* leftchild;
  node* rightchild;
  node(char c):data(c),leftchild(nullptr),rightchild(nullptr){}
};


node* build(string s1,string s2){//根据先序+中序,构造二叉树
  if(s1.size()==0)return nullptr;
  char c=s1[0];
  node* root=new node(c);
  int pos=s2.find(c);//找到分界点,pos也是左子树的长度
  
  root->leftchild=build(s1.substr(1,pos),s2.substr(0,pos));
  root->rightchild=build(s1.substr(pos+1),s2.substr(pos+1));
  return root;
}

void LRN(node* root){//后序访问
  if(root==nullptr)return;
  LRN(root->leftchild);
  LRN(root->rightchild);
  printf("%c",root->data);
}

int main(){
  string s1,s2;
  while(cin>>s1>>s2){
    node* root=build(s1,s2);
    LRN(root);
    printf("\n");

  }
  
  return 0;
}

全部评论

相关推荐

皮格吉:不,有的厂子面试无手撕,可以试试。都是一边学一边面。哪有真正准备好的时候,别放弃
无实习如何秋招上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务