标签:
// // main.cpp // subStructureInTree // // Created by Hugo Cao on 15/7/10. // Copyright (c) 2015年 Hugo Cao . All rights reserved. // /* 问题描述: 二叉树的镜像: 围绕着中心轴做左右调换。 就这么短短多几行代码,做递归就可以了。 void mirrorRecuresiveriy(binTree bt) { //判断是否为空,或者是子节点为空。 if (bt == NULL || (bt->m_pleft == NULL && bt->m_pright == NULL)) { return ; } //交换左右子树的位置 binTree pTemp = bt->m_pleft; bt->m_pleft = bt->m_pright; bt->m_pright = pTemp; //传入左结点。 if (bt->m_pleft) mirrorRecuresiveriy(bt->m_pleft); //传入右结点。 if (bt->m_pright) mirrorRecuresiveriy(bt->m_pright); } */ #include <iostream> using namespace std; #define Data int typedef struct binaaryTreeNode { Data m_value; binaaryTreeNode *m_pleft; binaaryTreeNode *m_pright; }btNode, *binTree; binTree addNode(Data value) { binTree bt = NULL; bt = new btNode; if (bt == NULL) { cout << "申请地址错误" << endl; return NULL; } bt->m_value = value; bt->m_pleft = NULL; bt->m_pright = NULL; return bt; } bool connectTreeNode(binTree parrentNode, binTree leftSonNode = NULL, binTree rightSonNode = NULL) { if (parrentNode == NULL || (leftSonNode == NULL && rightSonNode == NULL)) { cout << "结点输入问题" << endl; return false; } parrentNode->m_pleft = leftSonNode; parrentNode->m_pright = rightSonNode; return true; } binTree createBinaryATree(binTree Ahead) { binTree p1 = addNode(8); binTree p2 = addNode(8); binTree p3 = addNode(7); binTree p4 = addNode(9); binTree p5 = addNode(2); binTree p6 = addNode(4); binTree p7 = addNode(7); connectTreeNode(p1, p2, p3); connectTreeNode(p2, p4, p5); connectTreeNode(p5, p6, p7); return (Ahead = p1); } //树的镜像。 void mirrorRecuresiveriy(binTree bt) { //判断是否为空,或者是子节点为空。 if (bt == NULL || (bt->m_pleft == NULL && bt->m_pright == NULL)) { return ; } //交换左右子树的位置 binTree pTemp = bt->m_pleft; bt->m_pleft = bt->m_pright; bt->m_pright = pTemp; //传入左结点。 if (bt->m_pleft) mirrorRecuresiveriy(bt->m_pleft); if (bt->m_pright) mirrorRecuresiveriy(bt->m_pright); } void RLR_print_BinaryTree(binTree bt) { if (bt == NULL) return ; cout << bt->m_value << " " << endl; RLR_print_BinaryTree(bt->m_pleft); RLR_print_BinaryTree(bt->m_pright); } int main() { binTree bt_A = NULL; bt_A = createBinaryATree(bt_A); RLR_print_BinaryTree(bt_A); cout << endl; mirrorRecuresiveriy(bt_A); RLR_print_BinaryTree(bt_A); return 0; }
标签:
原文地址:http://www.cnblogs.com/hgonlywj/p/4842564.html