Leetcode 之Construct Binary Tree(52)
根据先序和中序构造二叉树、根据中序和后序构造二叉树,基础题,采用递归的方式解决,两题的方法类似。需要注意的是迭代器的用法。
//先序和中序 TreeNode *buildTree(vector<int>& preorder, vector<int>& inorder) { return buildTree(begin(preorder), end(preorder), begin(inorder), begin(inorder)); } template<typename InputIterator> TreeNode *buildTree(InputIterator pre_first, InputIterator pre_last, InputIterator in_first, InputIterator in_last) { if (pre_first == pre_last)return nullptr; if (in_first == in_last)return nullptr; //先序第一个为根结点 auto root = new TreeNode(*pre_first); //查找根结点在中序的位置,返回的是迭代器 auto intRootPos = find(in_first, in_last, *pre_first); //得到根结点的左半部分 auto leftSize = distance(in_first, intRootPos); //递归构造,注意去掉根结点 root->left = buildTree(next(pre_first), next(pre_first, leftSize), in_first, next(in_first, leftSize)); root->right = buildTree(next(pre_first, leftSize), pre_last, next(intRootPos), in_last); return root; }
//中序和后序 TreeNode *buildTree1(vector<int>& inorder, vector<int>& postorder) { return buildTree1(begin(inorder), end(inorder), begin(postorder), begin(postorder)); } template<typename InputIterator> TreeNode *buildTree1(InputIterator in_first, InputIterator in_last, InputIterator post_first, InputIterator post_last) { if (in_first == in_last)return nullptr; if (post_first == post_last)return nullptr; //后序最后一个为根结点 const auto val = *prev(post_last) auto root = new TreeNode(val); //查找根结点在中序的位置,返回的是迭代器 auto intRootPos = find(in_first, in_last, val); //得到根结点的左半部分 auto leftSize = distance(in_first, intRootPos); //递归构造,注意去掉根结点 root->left = buildTree(in_first, intRootPos, post_first, next(post_first, leftSize)); root->right = buildTree(next(intRootPos), in_last, next(post_first,leftSize), prev(post_last)); return root; }