力扣算法学习day14-3
106-从中序与后序遍历序列构造二叉树
题目
代码实现
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
int[] index = new int[1];
index[0] = postorder.length-1;
return nodeTraversal(0,inorder.length-1,inorder,index,postorder);
}
public TreeNode nodeTraversal(int left,int right,int[] inorder,int[] index,int[] postorder){
if(left > right){
return null;
}
int rootValue = postorder[index[0]];
TreeNode root = new TreeNode(rootValue);
if(right == left){
return root;
}
int rootIndex = 0;
for(int i = left;i <= right;i++){
if(inorder[i] == rootValue){
rootIndex = i;
}
}
index[0] = index[0] - 1;
TreeNode rightNode = nodeTraversal(rootIndex+1,right,inorder,index,postorder);
if(rightNode == null){
index[0] = index[0] + 1;
}
index[0] = index[0] - 1;
TreeNode leftNode = nodeTraversal(left,rootIndex-1,inorder,index,postorder);
if(leftNode == null){
index[0] = index[0] + 1;
}
root.left = leftNode;
root.right = rightNode;
return root;
}
}
105-从前序与中序遍历序列构造二叉树
题目
代码实现
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
int[] index = new int[1];
index[0] = 0;
return nodeTraversal(0,preorder.length-1,inorder,index,preorder);
}
public TreeNode nodeTraversal(int left,int right,int[] inorder,int[] index,int[] preorder){
if(left > right){
return null;
}
int rootValue = preorder[index[0]];
TreeNode root = new TreeNode(rootValue);
if(left == right){
return root;
}
int rootIndex = 0;
for(int i = left;i <= right;i++){
if(inorder[i] == rootValue){
rootIndex = i;
}
}
index[0] = index[0] + 1;
TreeNode leftNode = nodeTraversal(left,rootIndex-1,inorder,index,preorder);
if(leftNode == null){
index[0] = index[0] - 1;
}
index[0] = index[0] + 1;
TreeNode rightNode = nodeTraversal(rootIndex+1,right,inorder,index,preorder);
if(rightNode == null){
index[0] = index[0] - 1;
}
root.left = leftNode;
root.right = rightNode;
return root;
}
}
已复习 206-反转链表
|