題目
根據一棵樹的中序遍歷與後序遍歷構造二叉樹。
注意:
你可以假設樹中沒有重複的元素。
例如,給出
中序遍歷 inorder = [9,3,15,20,7]
後序遍歷 postorder = [9,15,7,20,3]
返回如下的二叉樹:
3
/ \
9 20
/ \
15 7
解題思路
“後序找根,劃分左右”。具體的,通過後序遍歷我們可以找到root,根據root我們可以在中序遍歷中找到當前root對應的左右子樹,再遞歸對當前root的左右子樹進行構造。所以構建二叉樹的問題流程就是:
1)找到各個子樹的根節點 root;
2)構建該根節點的左子樹;
3)構建該根節點的右子樹。
(類似題目:105. 從前序與中序遍歷序列構造二叉樹)
代碼
Python代碼如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
if not inorder or not postorder:
return None
root = TreeNode(postorder[-1])
root_idx = inorder.index(postorder[-1])
# 遞歸地構建左子樹
root.left = self.buildTree(inorder[:root_idx], postorder[:root_idx])
# 遞歸地構建右子樹
root.right = self.buildTree(inorder[root_idx+1:], postorder[root_idx:-1])
return root
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 myBuildTree(int[] inorder, int[] postorder, int inleft, int inright, int postleft, int postright, Map<Integer, Integer> map){
if(inleft > inright || postleft > postright){
return null;
}
TreeNode root = new TreeNode(postorder[postright]);
int root_idx = map.get(postorder[postright]);
root.left = myBuildTree(inorder, postorder, inleft, root_idx-1, postleft, root_idx-inleft+postleft-1, map);
root.right = myBuildTree(inorder, postorder, root_idx+1, inright, root_idx-inleft+postleft, postright-1, map);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
int n = inorder.length;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<n; i++){
map.put(inorder[i], i);
}
return myBuildTree(inorder, postorder, 0, n-1, 0, n-1, map);
}
}