[LeetCode] Binary Tree Postorder Traversal, leetcodepostorder
[Question]
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, cocould you do it iteratively?
[Code]
/********************************** Date: question: Binary Tree Postorder Traversal * Source: https://oj.leetcode.com/problems/binary-tree-postorder-traversal/* result: AC * Source: LeetCode * conclusion: * *********************************/# 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 {// traverse the left subtree while (p! = NULL) {stack. push (p); p = p-> left;} q = NULL; while (! Stack. empty () {p = stack. top (); stack. pop (); // whether the right subtree is null or if (p-> right = q) {v. push_back (p-> val); // retained the accessed node q = p;} else {// the current node cannot be accessed, and the p node re-enters the stack. push (p); // process the right subtree p = p-> right; break;} // if} // while} while (! Stack. empty (); // while return v ;}}; // create a binary tree int CreateBTree (TreeNode * & T) {char data; // enter the value of the node in the binary tree in the First Order (one character). '#' indicates the empty tree cin> data; if (data = '#') {T = NULL;} else {T = (TreeNode *) malloc (sizeof (TreeNode); // generate the root node T-> val = data-'0 '; // construct the left subtree CreateBTree (T-> left); // construct the right subtree 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 ;}}