[LeetCode]Binary Tree Postorder Traversal,leetcodepostorder
【題目】
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?
【代碼】
/********************************** 日期:2014-12-07* 作者:SJF0115* 題號: Binary Tree Postorder Traversal* 來源:https://oj.leetcode.com/problems/binary-tree-postorder-traversal/* 結果:AC* 來源:LeetCode* 總結:**********************************/#include <iostream>#include <malloc.h>#include <vector>#include <stack>using namespace std;struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public: vector<int> postorderTraversal(TreeNode *root) { vector<int> v; stack<TreeNode *> stack; TreeNode *p = root; TreeNode *q; do{ //遍曆左子樹 while(p != NULL){ stack.push(p); p = p->left; } q = NULL; while(!stack.empty()){ p = stack.top(); stack.pop(); // 右子樹是否為空白或者已訪問過 if(p->right == q){ v.push_back(p->val); //保留訪問過的節點 q = p; } else{ //當前節點不能訪問,p節點重新入棧 stack.push(p); //處理右子樹 p = p->right; break; }//if }//while }while(!stack.empty());//while return v; }};//按先序序列建立二叉樹int CreateBTree(TreeNode* &T){ char data; //按先序次序輸入二叉樹中結點的值(一個字元),‘#’表示空樹 cin>>data; if(data == '#'){ T = NULL; } else{ T = (TreeNode*)malloc(sizeof(TreeNode)); //產生根結點 T->val = data-'0'; //構造左子樹 CreateBTree(T->left); //構造右子樹 CreateBTree(T->right); } return 0;}int main() { Solution solution; TreeNode* root(0); CreateBTree(root); vector<int> v = solution.postorderTraversal(root); for(int i = 0;i < v.size();i++){ cout<<v[i]<<endl; }}