反转二叉树,即交换所有结点的左右子树,但不能使用递归方法。
解析:既然不能使用递归那么可以使用栈,代码如下:
#include <iostream> #include<stack> #include<assert.h> #include <tchar.h> #include <queue> using namespace std; typedef struct BinaryTreeNode { int m_nValue; BinaryTreeNode *m_pLeft; BinaryTreeNode *m_pRight; }BinaryTreeNode ; //以先序的方式构建二叉树,输入-1表示结点为空 void CreateBinaryTree(BinaryTreeNode *&pRoot) { int nNodeValue = 0; cin >> nNodeValue; if (-1== nNodeValue) { pRoot = NULL; return; } else { pRoot = new BinaryTreeNode(); pRoot->m_nValue = nNodeValue; CreateBinaryTree(pRoot->m_pLeft); CreateBinaryTree(pRoot->m_pRight); } } void ReserveBitree(BinaryTreeNode *pRoot) { /* if(pRoot==NULL) exit(0); */ assert(pRoot!=NULL); stack<BinaryTreeNode *> s; s.push(pRoot); while(!s.empty()) { BinaryTreeNode * tn = s.top(); s.pop(); BinaryTreeNode * tmp = tn->m_pLeft; tn->m_pLeft= tn->m_pRight; tn->m_pRight= tmp; if(tn->m_pLeft != NULL) s.push(tn->m_pLeft); if(tn->m_pRight != NULL) s.push(tn->m_pRight); } } void PrintInOrder(BinaryTreeNode *pRoot) { if (pRoot != NULL) { PrintInOrder(pRoot->m_pLeft); cout << pRoot->m_nValue << " "; PrintInOrder(pRoot->m_pRight); } } int _tmain(int argc, _TCHAR* argv[]) { BinaryTreeNode *pRoot = NULL; CreateBinaryTree(pRoot); cout <<"中序遍历为:"<<endl; PrintInOrder(pRoot); cout << endl; ReserveBitree(pRoot); cout <<"中序遍历为:"<<endl; PrintInOrder(pRoot); cout<<endl; system("pause"); return 0; }
原文地址:http://blog.csdn.net/u014082714/article/details/45190681