二叉树镜像

来源:互联网 发布:雷欧奥特曼mac装备 编辑:程序博客网 时间:2024/06/11 15:40
//根据前序遍历和中序遍历还原构造二叉树
//判断二叉树A是否包含二叉树B
//思路:1)首先遍历树A,找到一个节点值与B的根节点值相同
//       2)再以步骤1)找到的节点值,开始比较树A的子树是包含树B
#include <iostream>#include <stack>using namespace std;//树的前序遍历int preOrder1[] = {10, 6, 4, 8, 14, 12, 16};//树的中序遍历int inOrder1[] =  {4, 6, 8, 10, 12, 14, 16};int preOrder2[] = {8,9,2};int inOrder2[] =  {9,8,2};typedef struct Node_{Node_ * left, * right;int data;bool visit;}Node;//重建二叉树Node * RebuildBTree(Node * & root,int preOrder[], int inOrder[], int n, int pl, int pr, int il, int ir){int i = 0;for (i = il;i <= ir; ++i){if (inOrder[i] == preOrder[pl]){break;}}int k = i - il;if (i <= ir){root = new Node();root->data = inOrder[i];}else{root = NULL;return root;}root->left = RebuildBTree(root->left,preOrder, inOrder, k,pl + 1 ,pl + k , il, i-1);root->right = RebuildBTree(root->right,preOrder, inOrder, ir - i ,pl + k + 1,pr, i+1, ir);return root;}void NonRecursionInorder(Node * root){if (!root){return;}stack<Node *> st;st.push(root);while(!st.empty()){Node * cur = st.top();while(cur){st.push(cur->left);cur = cur->left;}st.pop();if(!st.empty()){cur = st.top();st.pop();printf("%d ", cur->data);st.push(cur->right);}}}void MirrorTree(Node * & root){if(!root || !root->left && !root->right){return;}Node * tmp = root->left;root->left = root->right;root->right = tmp;if (root->left){MirrorTree(root->left);}if (root->right){MirrorTree(root->right);}}int main(){Node * ParentRoot = 0;Node * ChildRoot = 0;int n1 = sizeof(preOrder1) / sizeof(preOrder1[0]);ParentRoot = RebuildBTree(ParentRoot,preOrder1, inOrder1, n1, 0, n1-1, 0, n1 - 1);int n2 = sizeof(preOrder2) / sizeof(preOrder2[0]);ChildRoot = RebuildBTree(ChildRoot,preOrder2, inOrder2, n2, 0, n2-1, 0, n2 - 1);printf("parent原始树中序遍历:");NonRecursionInorder(ParentRoot);printf("\nparent镜像树中序遍历:");MirrorTree(ParentRoot);NonRecursionInorder(ParentRoot);printf("\nChild原始树中序遍历:");NonRecursionInorder(ChildRoot);printf("\nChild镜像树中序遍历:");MirrorTree(ChildRoot);NonRecursionInorder(ChildRoot);return 0;}


原创粉丝点击