Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7] postorder = [9,15,7,20,3]
Return the following binary tree:
3 / 9 20 / 15 7
-------------------------------------------------------------------------------------
就是从中序遍历和后序遍历构建二叉树。可以用递归方式。注意递归的终止条件。
和 leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal 几乎一样。
参考博客:http://www.cnblogs.com/grandyang/p/4296193.html
C++代码:
/** * 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 build(inorder,0,inorder.size()-1,postorder,0,postorder.size() - 1); } TreeNode *build(vector<int> &inorder,int ileft,int iright,vector<int> &postorder,int pleft,int pright){ if(ileft > iright ||pleft > pright) return NULL; //终止条件,就是当序列的长度为0时,递归终止。 int i = 0; TreeNode *cur = new TreeNode(postorder[pright]); for(i = ileft; i < inorder.size(); i++){ if(inorder[i] == cur->val) break; } cur->left = build(inorder,ileft,i-1,postorder,pleft,pleft + i - ileft - 1); cur->right = build(inorder,i + 1,iright,postorder,pleft + i - ileft,pright - 1); return cur; } };
还有一个方法,就是建立几个数组,保存分割后的数组。不过时间会很长。
C++代码:
/** * 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 build(inorder,postorder); } TreeNode *build(vector<int> &inorder,vector<int> &postorder){ if(inorder.size() == 0 || postorder.size() == 0) //递归条件,当然也可以加上if(inorder.size() == 1 || postorder.size() == 1)return cur;这个递归条件。 return NULL; int rootval = postorder.back(); TreeNode *cur = new TreeNode(rootval); int i = 0; for(i = 0; i < inorder.size(); i++){ if(inorder[i] == rootval) break; } vector<int> inleft,inright; vector<int> poleft,poright; for(int j = 0; j < i; j++){ inleft.push_back(inorder[j]); poleft.push_back(postorder[j]); } for(int j = i + 1; j < inorder.size(); j++){ inright.push_back(inorder[j]); } for(int j = i; j < postorder.size() - 1; j++){ poright.push_back(postorder[j]); } cur->left = build(inleft,poleft); cur->right = build(inright,poright); return cur; } };
这两个方法从算法上看是一样的,只是代码的实现不同而已。