鏈接:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/
難度:Medium
題目:106. 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.
翻譯:給定樹的中序遍歷和后序遍歷,構造二叉樹。 注意:樹中不存在重復項。
思路:本題與105. Construct Binary Tree from Preorder and Inorder Traversal類似。你要先知道
中序遍歷:左子樹,根節(jié)點,右子樹
后序遍歷:左子樹,右子樹,根節(jié)點
以如下這棵樹為例:
1
--------|-------
2 3
----|---- ----|----
4 5 6 7
前序遍歷 1245367
中序遍歷 4251637
后續(xù)遍歷 4526731
我們可以發(fā)現,對于后序遍歷來說,最后一個元素一定是根節(jié)點,也就是1。然后我們在中序遍歷的結果里面找到1所在的位置,那么它的左半部分就是其左子樹,右半部分就是其右子樹。
我們將中序遍歷左半部分425取出,同時發(fā)現后序遍歷的結果也在相應的位置上面,只是順序稍微不一樣,也就是452。我們可以發(fā)現,后序遍歷中的2就是該子樹的根節(jié)點。
上面說到了左子樹,對于右子樹,我們取出637,同時發(fā)現后序遍歷中對應的數據偏移了一格,并且順序也不一樣,為673。而3就是這顆右子樹的根節(jié)點。
重復上述過程,通過后續(xù)遍歷找到根節(jié)點,然后在中序遍歷數據中根據根節(jié)點拆分成兩個部分,同時將對應的后序遍歷的數據也拆分成兩個部分,重復遞歸,就可以得到整個二叉樹了。
參考代碼:
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
Map<Integer, Integer> inorderMap = new HashMap<Integer, Integer>();
for(int i=0; i<inorder.length; i++)
inorderMap.put(inorder[i],i);
return buildTree(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1, inorderMap);
}
public TreeNode buildTree(int[] inorder, int iLeft, int iRight, int[] postorder, int pLeft, int pRight, Map<Integer, Integer> inorderMap){
if(iLeft>iRight || pLeft>pRight)
return null;
TreeNode cur = new TreeNode(postorder[pRight]);
//int i = 0;
//for(i=iLeft; i<=iRight; i++)
// if(postorder[pRight]==inorder[i])
// break;
int i = inorderMap.get(postorder[pRight]);
cur.left = buildTree(inorder, iLeft, i-1, postorder, pLeft, pLeft+i-iLeft-1, inorderMap);
cur.right = buildTree(inorder, i+1, iRight, postorder, pLeft+i-iLeft, pRight-1, inorderMap);
return cur;
}
}