标签:二叉树 traversal 中序遍历 后序遍历 构造二叉树
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
基本思路:
人中序和后序遍历结果中,构造出二叉树。
中序遍历为: {左子树} 根 {右子树}
后序遍历为: {左子树} {右子树} 根
特点:后序遍历的最后一个元素为根
1. 利用此根,在中序遍历中找到根的位置。其左边为左子树的结点,右边为右子树的结点。
2. 利用矩离相等的原理(距离即,左子树元素的个数),在后续遍历序列中找到 左子树与右子树的分界点。
对左子树,和右子树,分别递归应用上面的步骤。
在leetcode上实际执行时间为49ms。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return helper(inorder, postorder, 0, inorder.size(), 0, postorder.size());
}
TreeNode *helper(const vector<int> &inorder, const vector<int> &postorder, int in_start, int in_stop, int post_start, int post_stop) {
if (in_start >= in_stop)
return 0;
int root_idx = in_start;
while (inorder[root_idx] != postorder[post_stop-1])
++root_idx;
TreeNode *root = new TreeNode(postorder[post_stop-1]);
root->left = helper(inorder, postorder, in_start, root_idx, post_start, post_start+root_idx-in_start);
root->right = helper(inorder, postorder, root_idx+1, in_stop, post_start+root_idx-in_start, post_stop-1);
return root;
}
};Construct Binary Tree from Inorder and Postorder Traversal -- leetcode
标签:二叉树 traversal 中序遍历 后序遍历 构造二叉树
原文地址:http://blog.csdn.net/elton_xiao/article/details/45580939