03
04/2015
[LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
Construct Binary Tree from Inorder and Postorder 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.
解题思路:
可以用递归的办法做。由后序遍历确定根节点,有中序遍历确定左右子树。每个子树有分别是一个后序遍历和一个中序遍历。代码如下。注意递归调用时位置的计算,后序遍历和中序遍历的长度一致。
/** * Definition for binary tree * 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 getTreeNode(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size()-1); } TreeNode *getTreeNode(vector<int> &inorder, int startInOrder, int endInOrder, vector<int> & postorder, int startPostOrder, int endPostOrder){ if(startInOrder == endInOrder){ return new TreeNode(postorder[startPostOrder]); }else if(startInOrder > endInOrder){ return NULL; }else{ int postNumber = postorder[endPostOrder]; //找到postNumber在中序遍历的位置 int inPosition=0; for(int i=startInOrder; i<=endInOrder; i++){ if(inorder[i]==postNumber){ inPosition=i; break; } } TreeNode* node = new TreeNode(postNumber); node->right = getTreeNode(inorder, inPosition+1,endInOrder, postorder, endPostOrder+inPosition-endInOrder, endPostOrder - 1); node->left = getTreeNode(inorder, startInOrder, inPosition-1, postorder, startPostOrder, inPosition - 1 - startInOrder + startPostOrder); return node; } } };
0 条评论