Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:2016开淘宝店卖什么 编辑:程序博客网 时间:2024/05/29 14:16

1.已知前序和中序

Given preorder and inorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

2.已知后序和中序

Given inorder and postorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.


思路:先得到root节点,对左右子树递归。

已知前序和中序或者意志后序和中序,中序是必须要知道的。它的关键点是找到中序的root结点为之,然后两边做递归即可。

1)已知前序和中序:

用递归的方式实现。首先找root节点,前序遍历的第一个节点就是root节点。然后在中序遍历中找到root的位置,之前的是左子树,之后的是右子树。再分别对左子树和右子树做递归。

2)已知后序和中序:

用递归的方式实现。找root节点,它是后序遍历的最后一个节点。在中序遍历中找root的位置,将中序遍历分为左右子树,然后分别做递归即可。

先序:root|左子树|右子树

中序:左子树|root|右子树

后序:左子树|右子树|root

#include <iostream>#include <vector>#include <stack>using namespace std;typedef struct BinaryTreeNode{char data;BinaryTreeNode *leftChild;BinaryTreeNode *rightChild;}Node;//根据前序和中序来创建二叉树void makeBinaryTree1(Node **root,char *preOrder,char *midOrder,int length){if(length == 0){(*root) = NULL;return;}(*root) = new Node;(*root)->data = *preOrder;char *rootplace = strchr(midOrder,(*root)->data);if(rootplace == NULL){printf("Wrong sample!");}int leftTreeLength = strlen(midOrder) - strlen(rootplace);int rightTreeLength = length - leftTreeLength -1;makeBinaryTree1(&(*root)->leftChild,preOrder+1,midOrder,leftTreeLength);makeBinaryTree1(&(*root)->rightChild,preOrder+leftTreeLength+1,rootplace+1,rightTreeLength);}//根据后序和中序来创建二叉树void makeBinaryTree2(Node **root,char *postOrder,char *midOrder,int length){if(length == 0){(*root) = NULL;return;}(*root) = new Node;(*root)->data = *(postOrder + length -1);char *rootplace = strchr(midOrder,(*root)->data);if(rootplace == NULL){printf("Wrong sample!");}int leftTreeLength = strlen(midOrder) - strlen(rootplace);int rightTreeLength = length - leftTreeLength -1;makeBinaryTree2(&(*root)->leftChild,postOrder,midOrder,leftTreeLength);makeBinaryTree2(&(*root)->rightChild,postOrder+leftTreeLength,midOrder+leftTreeLength+1,rightTreeLength);}









0 0
原创粉丝点击