2035: Leaf Nodes
Kate is learning about binary tree. She think she know everything you know about binary trees. Wait, you don't know binary tree? Find a book about data structures, and it will just take you about three minutes. Now here is a binary tree: 3 / / / / 2 4 / / / / / / 0 1 6 / / 5 Kate think she also know something that you may not notice. First, for some type of binary trees, only the leaf nodes have the meaning (leaf node is the node which has no sub trees, for the tree above, the leaf nodes are 0 1 5), an example is the Huffman Tree. Second, she guess that if you know the preorder traversal and the postorder traversal of a binary tree, you can ensure the leaf node of the tree, and their order. For the tree above, the preorder travesal is 3 2 0 1 4 6 5 and the postorder travesal is 0 1 2 5 6 4 3, the leaf nodes in order(from left to right) are 0 1 5. But now the problem is she just guess it, if you can find a way to print a tree's leaf nodes in order using its preorder traversal and postorder traversal, you can say "she is right!" Input SpecificationThe input file will contain one or more test cases. In each test case there is a integer n (0<=n <= 10000), indicating the tree have n nodes, then followed two lists of integers, either contains n integers in the range of 0 and n-1 (both included), the first list is the preorder traversal, and the other is the postorder traversal. Input is terminated by an interger -1; Output SpecificationFor each test case, print the tree's leaf nodes in order, each in a line. Sample Input7 3 2 0 1 4 6 5 0 1 2 5 6 4 3 -1 Sample Output0 1 5 思路是这样的,因为先根遍历是中左右,后根遍历是左右中,所以左都在右前面。在后根遍历的序列里,从前往后,比如,由于后根遍历第一个肯定是叶子,那么在先根遍历里找那个结点,它前面的就是中,全部标记为-1,所以它们肯定不是叶子。 算法里面主要是COUNT来记录序号,用-1标记,领会领会!
这个算法的正确性在于右子树的第一个肯定是叶子节点,由于在先序遍历和后序遍历中左都在右前面,那么当我们在B数组(后序遍历)中找到叶子节点,就在A数组(先序遍历)中把叶子的祖先都标号,标记为他们不是叶子。由于总是先遍历左边,那么我们这么标记也不会影响到右边的叶子。
#include<iostream> |
JOJ2035: Leaf Nodes
最新推荐文章于 2024-04-16 17:27:12 发布