重建二叉树
- 1、说明:
知道一棵树的前序序列和中序序列,进行重建这棵二叉树
- 2、思路分析
A:我们知道前序的遍历顺序是:根–左–右
中序的遍历顺序是左–根–右
因此在给定的前序序列中第一个数就是根,给定的中序序列中,中间就是根,左右是它的左右子树。我来用图进行说明下:
B:我们由图可以知道,经过第一轮的寻找后接下来的就利用递归就可实现了
- 3、 代码实现:
Node* RebuildBTree(int* preorder,int lenth,int* inorder,int start,int end)
{
if(preorder == NULL && inorder && lenth<0)
return NULL;
Node* root = new Node(preorder[0]);
if(start == end)
return root;
while(start < end)
{
if(inorder[start] == preorder[0])
break;
else
start++;
}
if(root->_left)
{
root->_left = RebuildBTree(preorder+1,lenth,inorder,start,start-1);
}
if(root->_right)
{
root->_right = RebuildBTree(preorder+1,lenth,inorder,start+1,end);
}
return root;
}
输入两棵二叉树A和B,判断B是不是A的结构。
- 1、思路分析
1)先在A中查找有没有和B中的根一样的节点
2)再判断此根的子树是不是和B有一样的结构
- 2、代码实现
bool HasCommonRoot(Node* roo1, Node* roo2)
{
if (root1 == NULL)
return false;
bool result = false;
if (root1 && root2)
{
if (root1->_data == root2->_data)
result = Tree1HasTree2(root1,root2);
if (!result)
result = HasCommonRoot(root1->_left, root2);
if (!result)
result = HasCommonRoot(root1->_right, root2);
}
return result;
}
bool Tree1HasTree2(Node* root1, Node* root2)
{
if (root1 == NULL)
return false;
if (root2 == NULL)
return true;
if (root1->_data == root2->_data)
return true;
return Tree1HasTree2(root1->_left, root2->_left) &&
Tree1HasTree2(root2->_right, root->_right);
}
二叉树的镜像
- 思路分析:
将遇到的左右两个子树进行交换即可,然后进行递归
- 代码实现:
void BTreeMirror(Node* root)
{
if