Idea: Data Structure
Analysis:
1. The question is given to the central sequence and post sequence of a binary tree to find the value of the leaf node in the shortest path from the root node to the leaf node, if multiple paths output the smallest leaf node
2. The topic says that there are a maximum of 10000 nodes. However, because the binary tree mentioned in the topic is not a Complete Binary Tree, the creation of a binary tree here cannot use the static idea. We should use the dynamic increase.
3. After a binary tree is created, the ans can be obtained by traversing in the forward order.
Code:
# Include <cstdio> # include <cstring> # include <iostream> # include <algorithm> using namespace std; const int INF = 1 <30; const int MAXN = 1000010; struct Node {int x; Node * left; Node * right; Node (int x) {this-> x = x; this-> left = NULL; this-> right = NULL ;}}; Node * root; char str [MAXN]; int nodeNum, ans, maxNum, stepNum; int midOrder [MAXN], postOrder [MAXN]; void getOrder (int * arr) {int len = strlen (str); nod ENum = 0; for (int I = 0; I <len; I ++) {int j = I; int num = 0; while (str [j]! = ''& J <len) {num = num * 10 + str [j]-'0'; j ++;} arr [nodeNum ++] = num; I = j ;}} Node * createTree (int * mid, int * post, int len) {if (len = 0) return NULL; int k = 0; while (mid [k]! = Post [len-1]) k ++; Node * root = new Node (post [len-1]); // left subtree root-> left = createTree (mid, post, k); // right subtree root-> right = createTree (mid + k + 1, post + k, len-k-1); return root;} void solve (int sum, int step, Node * node) {if (node! = NULL) {if (node-> left = NULL & node-> right = NULL) {if (maxNum> sum + node-> x) {maxNum = sum + node-> x; ans = node-> x;} else if (maxNum = sum + node-> x) ans = min (ans, node-> x);} solve (sum + node-> x, step + 1, node-> left); solve (sum + node-> x, step + 1, node-> right) ;}} int main () {while (gets (str) {getOrder (midOrder); gets (str); getOrder (postOrder ); root = createTree (midOrder, postOrder, nodeNum); maxNum = ans = INF; solve (0, 0, root); printf ("% d \ n", ans );} return 0 ;}