劍指offer第五天之重建二叉樹

劍指offer第五天之重建二叉樹
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
java:
在這裏插入圖片描述

int[] array = {1, 2, 3, 4, 5};
int[] arrayCopy = Arrays.copyOfRange(array, 0,3);
System.out.println(Arrays.toString(arrayCopy)); //[1, 2, 3]

在這裏插入圖片描述

import java.util.Arrays;
public class Solution {
     public TreeNode reConstructBinaryTree(int [] pre,int [] in)
    {
        if(pre.length==0)
            return null;
        int rootval = pre[0];
        //數組長度僅爲1的時候就要處理
        if(pre.length==1)
            return new TreeNode(rootval);
        TreeNode root = new TreeNode(rootval);
        int rootIndex = 0;
        //我們先找到root所在的位置,確定好前序和中序中左子樹和右子樹序列的範圍
        for(int i=0;i<in.length;i++)
        {
            if (in[i]==rootval)
            {
                rootIndex =i;
                break;
            }
        }
        //遞歸,假設root的左右子樹都已經構建完畢,那麼只要將左右子樹安到root左右即可
        //這裏注意Arrays.copyOfRange(int[],start,end)是[)的區間
        root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,rootIndex+1),Arrays.copyOfRange(in,0,rootIndex));
        root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,rootIndex+1,pre.length),Arrays.copyOfRange(in,rootIndex+1,in.length));
        return root;
    }
}

python:
在這裏插入圖片描述

lista =[1, 4, 9, 16, 25]
print(lista[:3])
print(lista[3+1:])

在這裏插入圖片描述

class Solution:
    # 返回構造的TreeNode根節點
    def reConstructBinaryTree(self, pre, tin):
        # write code here
        if not pre or not tin:
            return None
        root = TreeNode(pre.pop(0))
        index = tin.index(root.val)
        root.left = self.reConstructBinaryTree(pre, tin[:index])
        root.right = self.reConstructBinaryTree(pre, tin[index + 1:])
        return root

c++:

#include<iostream>
#include<string>
using namespace std;
typedef struct TreeNode{
    char data;
    struct TreeNode *lchild;
    struct TreeNode *rchild;
}*bitree;
void inorder(bitree root)
{
	if(root!=NULL)
	{
		inorder(root->lchild);	
		inorder(root->rchild);
		cout<<root->data;	
	} 
}
TreeNode *create_tree(string p,string m)
{
	bitree bt=new(TreeNode);
	if(p.length()==0||m.length()==0)
	{	 
		return NULL;
	}
	else
	{
		bt->data=p[0];
		int index=m.find(p[0]);
		bt->lchild=create_tree(p.substr(1,index),m.substr(0,index));
		bt->rchild=create_tree(p.substr(index+1),m.substr(index+1));
		return bt;
	}
} 
int main()
{
	bitree *bt;
	bt=new(bitree);
    string p,m;
    cin>>p>>m;
    *bt=create_tree(p,m);
	inorder(*bt);
	return 0;
}  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章