关于树的考察点:二叉树的深度、树的子结构、二叉树中和为某一值得路径、重建二叉树、二叉树的后序遍历序列。
二叉搜索树:树种两个结点的最低公共祖先、二叉树与双向链表
重建二叉树:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}。
typedef struct BinaryTreeNode{
int key;
BinaryTreeNode* left;
BinaryTreeNode* right;
} treenode;
treenode* construct(int* preoder,int* inorder,int length){
if(preoder == NULL || inorder==NULL || length<=0){
return NULL;
}
return construct_core(preoder,preoder+length-1,inorder,inorder+length-1);
}
treenode* construct_core(int* startprorder,int* endpreoreder,int* startinorder,int* endpinorder){
//创建根节点,从前序遍历中找到树的根节点
int rootvalue=startprorder[0];
treenode* root = (treenode*) malloc(sizeof(treenode));
root->key =rootvalue;
root->left=NULL;
root->right=NULL;
//如果此时就一个值的话
if(startprorder == endpreoreder){
if(startinorder == endpinorder && *startinorder==*startprorder)
return root;
else{
printf("所提供的数组值有问题!\n");
return NULL;
}
}
//将指针指向中序遍历的起始点
int* rootinorder = startinorder;
//开始遍历找到中序遍历的根节点所在的位置,搜索的情况是搜索不要超过原来搜索的数组长度,且值要找到相等的
while(*rootinorder!=rootvalue && rootinorder<=endpinorder){
rootinorder++;
}
if(rootinorder == endpinorder && *rootinorder != rootvalue){
printf("搜提供的数组值有问题!\n");
return NULL;
}
//算出左右子树的大小
int leftlength = rootinorder - startinorder;
int* left_preorder_end = startprorder + leftlength;//前序遍历中左子树结束的位置
//构建左子树,如果还有子节点则继续递归构建子树
if(leftlength>0){
root->left = construct_core(startprorder+1,left_preorder_end,startinorder,rootinorder-1);
}
//构建右子树,如果右侧还有子节点则继续递归构建子树
if(leftlength< endpreoreder - startprorder){
root->right = construct_core(left_preorder_end+1,endpreoreder,rootinorder+1,endpinorder);
}
return root;
}