这是刷leetcode以来第一次碰到了一道有关树的题 这种题一看就是要用到递归啦(遥想当年我一直不懂递归,直到学二叉树的时候 关于二叉树的操作基本上都要用上递归才学会了) 先序序列是 父节点->左孩子->右孩子 中序序列是 左孩子->父结点->右孩子 题目中 先序序列是 3,9,20,15,7 中序序列是
9,3,15,20,7 根据上述对先序中序的解释 我们可以知道 根节点是3 那
这时看一下中序序列 可以得到 3的左边是它左子树上的节点 右边是它右子树上的节点 这样整棵树就构建好了 再递归的去构建左子树和右子树 思路同上
struct TreeNode* build_Tree(int* preorder, int preorderSize, int* inorder, int inorderSize,int *root,int range1,int range2)
{
if(*root>=preorderSize)
return NULL;
if(range1>range2)
return NULL;
struct TreeNode* Root=(struct TreeNode*)malloc(sizeof(struct TreeNode));
Root->val=preorder[*root];
int i=0,index=0;
for(i=range1;i<=range2;i++)
{
if(inorder[i]==preorder[*root])//找到根节点
{
index=i;
break;
}
}
*root+=1;
Root->left=build_Tree(preorder,preorderSize,inorder,inorderSize,root,range1,index-1);
Root->right=build_Tree(preorder,preorderSize,inorder,inorderSize,root,index+1,range2);
return Root;
}
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){
if(preorderSize==0)//如果是一棵空树
return NULL;
int root=0;
return build_Tree(preorder,preorderSize,inorder,inorderSize,&root,0,inorderSize-1);
}
迭代
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
// 3,20,7 3,20,7
// preorder = {3,9,20,15,7}
// inorder = {9,3,15,20,7}
public TreeNode buildTree(int[] preorder, int[] inorder) {
Stack<TreeNode> stack = new Stack<>();
TreeNode root = new TreeNode(preorder[0]);
stack.push(root);
int inorderIndex = 0;
TreeNode node = null;
for(int i = 1; i < preorder.length;i++){
if(!stack.isEmpty() && stack.peek().val != inorder[inorderIndex]){
node = stack.peek();
node.left = new TreeNode(preorder[i]);
stack.push(node.left);
}
else{
while(!stack.isEmpty() && stack.peek().val == inorder[inorderIndex]){
node = stack.pop();
inorderIndex += 1;
}
node.right = new TreeNode(preorder[i]);
stack.push(node.right);
}
}
return root;
}
}
递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int preorderIndex = 0;
public TreeNode buildTree(int[] preorder, int[] inorder) {
return buildT(preorder,inorder,0,inorder.length-1);
}
public TreeNode buildT(int[] preorder,int[] inorder,int l,int r){
if(l > r)
return null;
int rootIndex = 0;
for(int i = l;i <= r;i++){
if(inorder[i] == preorder[preorderIndex]){
rootIndex = i;
break;
}
}
TreeNode root = new TreeNode(inorder[rootIndex]);
preorderIndex += 1;
root.left = buildT(preorder,inorder,l,rootIndex-1);
root.right = buildT(preorder,inorder,rootIndex+1,r);
return root;
}
}