- 题目:完成一个函数,输入一个二叉树,该函数输出他
结点定义如下
typedef struct TreeNode
{
TreeNode(char data)
:_pleft(NULL)
, _pright(NULL)
, _data(data)
{}
TreeNode *_pleft;
TreeNode *_pright;
char _data;
}Node;
实现思路:
1.交换8的左右孩子
2.交换6的左右孩子
3.交换10的左右孩子
函数实现结果如下:
由上述思路我们可以写出代码
创建树代码
void _CreateBinaryTree(Node *&pRoot, char *pStr, size_t size, size_t& index)
{//此处index一定要用引用
if (index < size && '#' != pStr[index])
{
pRoot = new Node(pStr[index]);
_CreateBinaryTree(pRoot->_pleft, pStr, size, ++index);
_CreateBinaryTree(pRoot->_pright, pStr, size, ++index);
}
}
非递归实现代码
Node *GetMirror_Nor(Node *pRoot)//二叉树镜像非递归
{
if (NULL == pRoot)
return NULL;
Node *pCur = pRoot;
queue<Node*> q;
q.push(pRoot);
while (!q.empty())
{
Node *front = q.front();
if (front->_pleft)
q.push(front->_pleft);
if (front->_pright)
q.push(front->_pright);
std::swap(front->_pleft, front->_pright);
q.pop();
}
return pCur;
}
递归实现
Node *GetMirror(Node *pRoot)
{
if (NULL == pRoot || (NULL == pRoot->_pleft && NULL == pRoot->_pright))
return NULL;
swap(pRoot->_pleft, pRoot->_pright);
if (pRoot->_pleft)
GetMirror(pRoot->_pleft);
if (pRoot->_pright)
GetMirror(pRoot->_pright);
return pRoot;
}