/*binary-tree-postorder-traversal*/ /***************************/ /* Given a binary tree, return the postorder traversal of its nodes‘ values. For example: Given binary tree{1,#,2,3}, 1 2 / 3 return[3,2,1]. Note: Recursive solution is trivial, could you do it iteratively? */ /****************************/ struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode(int x):val(x),left(NULL),right(NULL){} } vector<int> postorder(TreeNode *root) { stack<TreeNode *> s; vector<int> res; if(root==NULL) return res; s.push(root); while(!s.empty()){ ListNode *temp=s.top(); s.pop(); res.push_back(temp->val); if(temp->right!=NULL) s.push(temp->right); if(temp->left!=NULL) s.push(temp->left); } return res; }
时间: 2024-11-16 15:21:09