题解 | #二叉树遍历#

二叉树遍历

http://www.nowcoder.com/questionTerminal/4b91205483694f449f94c179883c1fef

  • 先序建立和先序遍历是类似的
  • 空指针可以用nullptr
#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 s,int& pos){//根据先序序列建立二叉树(序列,当前字符位置)
  char c=s[pos++];//每调用一次,pos都要++
  if(c=='#'){
    return nullptr;
  }
  node* root=new node(c);
  root->leftchild=build(s,pos);
  root->rightchild=build(s,pos);
  return root;
}

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

int main(){
  string s;
  while(cin>>s){
    int pos=0;
    node* root=build(s,pos);
    LNR(root);
    printf("\n");

  }
  
  return 0;
}

全部评论

相关推荐

RajahnRan:公司赚到了,这可是一眼就手写出来的代码,ai都写不出来
点赞 评论 收藏
分享
一天代码十万三:这个学历有中大厂实习也是0面,没办法,斩杀线是这样的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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