UVa548
Tree
给定二叉树的中序遍历和后序遍历结果,输出从根节点到叶节点的路径和最小的叶节点的值,如果有多个叶节点满足上述条件,则输出值较小的叶节点。
依次遍历后序遍历的结果,在中序遍历中查找该元素,该元素右侧的就是该节点的右子树,左侧的就是该节点的左子树。
#include#include #include #include #include #include #include using namespace std; struct Node { int value; shared_ptr left, right; }; class Solution { public: Solution(const vector &inorder, const vector &postorder) { vector ::const_reverse_iterator PostIter = postorder.crbegin(); ConstructBinaryTree(tree, inorder.begin(), inorder.end(), PostIter, postorder.rend()); } int GetLeafValue() { TraverseLeafNode(tree, 0); return LeafValue; } private: Node tree; int LeastSum = INT_MAX, LeafValue; void ConstructBinaryTree(Node &root, vector ::const_iterator begin, vector ::const_iterator end, vector ::const_reverse_iterator &PostIter, vector ::const_reverse_iterator PostEnd) { root.value = *PostIter++; vector ::const_iterator RootIter = find(begin, end, root.value); if (RootIter + 1 != end) { root.right = make_shared (); ConstructBinaryTree(*root.right, RootIter + 1, end, PostIter, PostEnd); } if (begin != RootIter) { root.left = make_shared (); ConstructBinaryTree(*root.left, begin, RootIter, PostIter, PostEnd); } } void TraverseLeafNode(const Node &root, int sum) { if (root.left == nullptr && root.right == nullptr) { if (sum + root.value < LeastSum) { LeastSum = sum + root.value; LeafValue = root.value; } else if (sum + root.value == LeastSum) { LeafValue = min(LeafValue, root.value); } return; } if (root.left != nullptr) { TraverseLeafNode(*root.left, sum + root.value); } if (root.right != nullptr) { TraverseLeafNode(*root.right, sum + root.value); } } }; vector ConverseInput(const string &input) { vector ret; stringstream ss(input); int value; while (ss >> value) { ret.push_back(value); } return ret; } int main() { string input; while (getline(cin, input)) { vector inorder = ConverseInput(input), postorder; getline(cin, input); postorder = ConverseInput(input); Solution solution(inorder, postorder); cout << solution.GetLeafValue() << endl; } return 0; }



