structTreeNode { TreeNode* left; TreeNode* right; int val; };
boolcheck(vector<bool> ls){ int count = ls.size(); int cnt = 0; for (int i = 1; i < count; i++) { if (ls[i-1] != ls[i]) cnt++; if (cnt > 1) returnfalse; } returntrue; }
boolbuild(vector<int> f_ord, TreeNode* root, bool left_smaller){ int size = f_ord.size(); root->val = f_ord[0]; if (size == 1) { root->left = nullptr; root->right = nullptr; returntrue; } TreeNode* l = new TreeNode(); TreeNode* r = new TreeNode(); vector<int> l_f_ord,r_f_ord; vector<bool> to_left(size, false); for (int i = 1; i < f_ord.size(); i++) { if ((f_ord[i] < root->val) == left_smaller) { r_f_ord.push_back(f_ord[i]); // 左子树 to_left[i] = true; } else { l_f_ord.push_back(f_ord[i]); // 右子树 to_left[i] = false; } } //检查是否合法,to_left应该形如1 1 1 0 0 0 或者 0 0 0 1 1 1 if (!check(to_left)) returnfalse; if (!l_f_ord.empty()) { bool b = build(l_f_ord, l, left_smaller); if (!b) returnfalse; } else l = nullptr; if (!r_f_ord.empty()) { bool b = build(r_f_ord, r, left_smaller); if (!b) returnfalse; } else r = nullptr; root->left = l; root->right = r; returntrue; }
voidvisit(TreeNode* root){ // 后序遍历 if (root->left) visit(root->left); if (root->right) visit(root->right); cout << root->val << ' '; }