引言:已知一颗二叉树的前序、中序、后序遍历,我们知道如何还原出这颗二叉树,那么我们使用Java代码如何实现?
备注: 根据二叉树的先序、中序、后序遍历构建二叉树-图文详解
class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
}
根据二叉树的前序、中序遍历还原二叉树
public TreeNode buildTree (int[] preorder, int[] inorder) {
return buildNode(preorder,0,preorder.length,inorder,0,inorder.length);
}
private TreeNode buildNode(int[] preorder,int preLeft,int preRight,int[] inorder,int inLeft,int inRight){
if(inRight - inLeft < 1){
return null;
}
if(inRight - inLeft == 1) {
return new TreeNode(inorder[inLeft]);
}
int rootVal = preorder[preLeft];
TreeNode rootNode = new TreeNode(rootVal);
int rootIndex = 0;
for (int i = inLeft; i < inRight ; i++) {
if(inorder[i] == rootVal){
rootIndex = i;
break;
}
}
int length = rootIndex - inLeft;
rootNode.left = buildNode(preorder,preLeft + 1,preLeft + 1 + length,inorder,inLeft,rootIndex);
rootNode.right = buildNode(preorder,preLeft + 1 + length,preRight,inorder,rootIndex + 1,inRight);
return rootNode;
}
根据二叉树的中、后序遍历还原二叉树
public TreeNode buildTree (int[] inorder, int[] postorder) {
return buildNode(inorder,0,inorder.length,postorder,0,postorder.length);
}
private TreeNode buildNode(int[] inorder,int inLeft,int inRight,int[] postorder,int postLeft,int postRight){
if(inRight - inLeft < 1){
return null;
}
if(inRight - inLeft == 1) {
return new TreeNode(inorder[inLeft]);
}
int rootVal = postorder[postRight - 1];
TreeNode rootNode = new TreeNode(rootVal);
int rootIndex = 0;
for (int i = inLeft; i < inRight ; i++) {
if(inorder[i] == rootVal){
rootIndex = i;
break;
}
}
int length = rootIndex - inLeft;
rootNode.left = buildNode(inorder,inLeft,rootIndex,postorder,postLeft,postLeft + length);
rootNode.right = buildNode(inorder,rootIndex + 1,inRight,postorder,postLeft + length, postRight - 1);
return rootNode;
}
|