題目來源:LeetCode
根據一棵樹的前序遍歷與中序遍歷構造二叉樹。
/**
* 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[] preorder, int[] inorder) {
if(preorder.length == 0){ //判斷樹是否爲空
return null;
}
int rootValue = preorder[0]; //根結點就是前序遍歷preorder的第一個元素
int LeftCount;
for(LeftCount = 0; LeftCount < inorder.length; LeftCount++){
if(inorder[LeftCount] == rootValue){//在中序遍歷inorder中找到根結點
break;
}
}
TreeNode root = new TreeNode(rootValue); //將根結點的值裝入結點
//將preorder中的元素從preorder[1]到preorder[1 + LeftCount](左開右閉,不包括後者)拷貝到新的數組leftPreorder中
int[] leftPreorder = Arrays.copyOfRange(preorder, 1, 1 + LeftCount);
//將inorder中的元素從inorder[0]到inorder[LeftCount]拷貝到leftInorder中
int[] leftInorder = Arrays.copyOfRange(inorder, 0, LeftCount);
//遞歸
root.left = buildTree(leftPreorder,leftInorder);
//同理,寫出右子樹的過程
int[] rightPreorder = Arrays.copyOfRange(preorder, LeftCount + 1, preorder.length);
int[] rightInorder = Arrays.copyOfRange(inorder, LeftCount + 1, inorder.length);
root.right = buildTree(rightPreorder,rightInorder);
return root;
}
}
同理可寫出從中序與後序遍歷序列構造二叉樹的代碼:
/**
* 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) {
if(inorder.length == 0){
return null;
}
int rootValue = postorder[postorder.length - 1];
int LeftCount;
for(LeftCount = 0; LeftCount < inorder.length; LeftCount++){
if(inorder[LeftCount] == rootValue){
break;
}
}
TreeNode root = new TreeNode(rootValue);
//這裏注意Arrays.copyOfRange()方法拷貝時的範圍是:左閉右開
int[] leftInorder = Arrays.copyOfRange(inorder, 0, LeftCount);
int[] leftPostorder = Arrays.copyOfRange(postorder, 0, LeftCount);
root.left = buildTree(leftInorder, leftPostorder);
int[] rightInorder = Arrays.copyOfRange(inorder, LeftCount + 1, postorder.length);
int[] rightPostorder = Arrays.copyOfRange(postorder, LeftCount, postorder.length - 1);
root.right = buildTree(rightInorder, rightPostorder);
return root;
}
}