Title Source: http://www.lintcode.com/zh-cn/problem/binary-tree-postorder-traversal/#
C + + version VS2012 Test passed
1 //#include <iostream>2 //#include <vector>3 //using namespace std;4 5 //Definition of TreeNode6 //class TreeNode {7 //Public :8 //int val;9 //TreeNode *left, *right;Ten //TreeNode (int val=-1) { One //this->val = val; A //This->left = This->right = NULL; - // } - //}; the - //Enter a pre-order traversal to create a two-fork tree - //example Input abdh#k## #E # #CFI # # #G #j## - //void Createbitree (TreeNode **t)//*t is a pointer to Bitnode + //{ - //*t=new TreeNode; + //if (*t==null)//if *t still points to null, indicating memory allocation failure, exiting the program A //exit (OVERFLOW); at //Char ch; - //cin>>ch; - //if (ch== ' # ') - //*t=null; - //Else - // { in //Createbitree (& (*t)->left);//Create & (*t)->lchild temporary variable, pass in Createbitree, construct left subtree - //Createbitree (& (*t)->right);//Create & (*t)->rchild temporary variable, pass in Createbitree, construct right subtree to //(*t)->val=ch;//The data assignment for the node that *t points to, which is to generate the root node + // } - //} the * classSolution { $ Public:Panax Notoginseng /** - * @param root:the root of binary tree. the * @return: Preorder in vector which contains node values. + */ Avector<int>Preorder; the voidTraverse (TreeNode *root) { + if(Root = =NULL) { - return; $ } $Traverse (root->Left ); -Traverse (root->Right ); -Preorder.push_back (root->val); the } -vector<int> Postordertraversal (TreeNode *root) {Wuyi //Write your code here the preorder.clear (); - traverse (root); Wu returnPreorder; - } About }; $ - //Test - //int main () - //{ A //solution S; + //vector<int> Preorder; the // - //TreeNode **pp;//defines a two-level pointer to Bitnode pp $ //TreeNode *p;//defines a pointer to bitnode p the //pp=&p;//pp Pointing P the //P=null;//initialize p to point to null the //Createbitree (PP);//Pass in the address pointing to p to create a two-fork tree the // - //preorder=s.postordertraversal (p);//incoming address to Bitnode, pre-order traversal creates a good two-fork tree in //for (int i=0;i<preorder.size (); i++) the //Putchar (preorder.at (i)); the //}
[Easy] sequential traversal of binary trees