二叉树构造定理:
- 定理7.1:任何n(n>0)个不同结点的二又树,都可由它的中序序列和先序序列唯一地确定。
- 定理7.2:任何n(n>0)个不同结点的二又树,都可由它的中序序列和后序序列唯一地确定。
1.1 已知先序序列为ABDGCEF,中序序列为DGBAECF,则构造二叉树的过程如下所示。
1.1.1 C代码:
#include<stdio.h>
#include<malloc.h>typedef struct node
{struct node *lchild, *rchild;char data;
} BTNode;BTNode* CreateBTree(char *pre, char *in, int n)
{int k;char *p;if (n <= 0)return NULL;BTNode *b = (BTNode*)malloc(sizeof(BTNode));b->data = *pre;for (p = in; p < in + n; ++p)if (*p == *pre)break;k = p-in;b->lchild = CreateBTree(pre+1, in, k);b->rchild = CreateBTree(pre+k+1, p+1, n-k-1);return b;
}void dispBTree(BTNode *b)
{if(b!= NULL){printf("%c", b->data);if(b->lchild != NULL || b->rchild != NULL){printf("(");dispBTree(b->lchild); if(b->rchild != NULL)printf(",");dispBTree(b->rchild);printf(")"); }}} int main()
{BTNode* b;char pre[] = "ABDGCEF";char in[] = "DGBAECF";int n = 7;b = CreateBTree(pre, in, 7);dispBTree(b);return 0;
}
1.1.2 C++代码:
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {TreeNode *b = CreateBTree(preorder.begin(), inorder.begin(), inorder.size());return b; }TreeNode* CreateBTree(vector<int>::iterator p, vector<int>::iterator q, int n){TreeNode *b;auto s = q;int k;if(n <= 0)return nullptr;b = new TreeNode(*p);for(; s < q + n; ++s)if(*s == *p)break;k = s - q;b->left = CreateBTree(p+1, q, k);b->right = CreateBTree(p+k+1, s+1, n-k-1);return b;}
};