清华大学机试 二叉树遍历 Easy *根据先序序列构建二叉树,没怎么见过
基本思想:
根据完整的遍历序列进行生成二叉树,其中空节点置空处理使得构建成为可能,不再需要两个序列同时决定;
关键点:
注意构建的问题;
#include<stdio.h> #include<stdlib.h> #include<iostream> #include<string> #include<vector> #include<algorithm> #include<map> #include<set> using namespace std; int index = 0; struct node { char data; node* left=NULL; node* right=NULL; }; node* bulid(string s) { if (index>=s.size()||s[index] == '#') { index++; return NULL; } node* no = new node; no->data = s[index++]; no->left = bulid(s); no->right = bulid(s); return no; } void binorder(node* root) { if (root == NULL) return; binorder(root->left); cout << root->data << " "; binorder(root->right); } int main() { string s; while (cin >> s) { node* root = NULL; root = bulid(s); binorder(root); } return 0; }

浙公网安备 33010602011771号