problemscpp
A collection of my answers to algorithm problems in c++.
| 函数
pat::a::a1020 命名空间参考

1020 Tree Traversals 更多...

struct  TreeNode
 

函数

int main (istream &cin, ostream &cout)
 
TreeNodeparse (vector< unsigned int > post_order, const vector< unsigned int > &in_order)
 
 TEST (a1020, case1)
 

详细描述

1020 Tree Traversals

函数说明

◆ main()

int pat::a::a1020::main ( istream &  cin,
ostream &  cout 
)

在文件 pat.cpp4820 行定义.

4820 {
4821 unsigned n;
4822 cin >> n;
4823 vector<unsigned> post_order(n);
4824 vector<unsigned> in_order(n);
4825 for(unsigned i = 0; i < n; i++) {
4826 cin >> post_order[i];
4827 }
4828 for(unsigned i = 0; i < n; i++) {
4829 cin >> in_order[i];
4830 }
4831 TreeNode *root = parse(post_order, in_order);
4832 queue<TreeNode *> q;
4833 q.push(root);
4834 bool flag = true;
4835 while(!q.empty()) {
4836 const auto node = q.front();
4837 q.pop();
4838 if(flag) {
4839 flag = false;
4840 cout << node->key;
4841 } else {
4842 cout << ' ' << node->key;
4843 }
4844 if(node->left != nullptr) {
4845 q.push(node->left);
4846 }
4847 if(node->right != nullptr) {
4848 q.push(node->right);
4849 }
4850 }
4851 return 0;
4852 }
vector< int > root
Definition: acwing408.cpp:349
TreeNode * parse(vector< unsigned int > post_order, const vector< unsigned int > &in_order)
Definition: pat.cpp:4854

引用了 parse() , 以及 acwing::acwing836_408::root.

被这些函数引用 TEST().

◆ parse()

TreeNode * pat::a::a1020::parse ( vector< unsigned int >  post_order,
const vector< unsigned int > &  in_order 
)

在文件 pat.cpp4854 行定义.

4854 {
4855 const auto root = new TreeNode(post_order.back());
4856 bool in_left = true;
4857 unordered_set<unsigned> left, right;
4858 vector<unsigned> left_post, right_post, left_in, right_in;
4859 for(auto node: in_order) {
4860 if(in_left) {
4861 if(node == root->key) {
4862 in_left = false;
4863 } else {
4864 left.insert(node);
4865 left_in.emplace_back(node);
4866 }
4867 } else {
4868 right.insert(node);
4869 right_in.emplace_back(node);
4870 }
4871 }
4872 for(auto node: post_order) {
4873 if(node == root->key) {
4874 continue;
4875 }
4876 if(left.contains(node)) {
4877 left_post.emplace_back(node);
4878 } else {
4879 right_post.emplace_back(node);
4880 }
4881 }
4882 if(!left.empty()) {
4883 root->left = parse(left_post, left_in);
4884 }
4885 if(!right.empty()) {
4886 root->right = parse(right_post, right_in);
4887 }
4888 return root;
4889 }

引用了 acwing::acwing1929::left, parse(), acwing::acwing1929::right , 以及 acwing::acwing836_408::root.

被这些函数引用 main() , 以及 parse().

◆ TEST()

pat::a::a1020::TEST ( a1020  ,
case1   
)

在文件 pat_test.cpp2199 行定义.

2199 {
2200 istringstream in("7\n"
2201 "2 3 1 5 7 6 4\n"
2202 "1 2 3 4 5 6 7");
2203 auto out = ostringstream();
2204 main(in, out);
2205 ASSERT_EQ("4 1 6 3 5 7 2", out.str());
2206 }
int main(int argc, char **argv)
Definition: main.cpp:5

引用了 main().