binary-tree-postorder-traversa 迭代求解二叉树后序遍历

题目:

求给定的二叉树的后序遍历。
例如:
给定的二叉树为{1,#,2,3},
返回[3,2,1].
备注;用递归来解这道题太没有新意了,可以给出迭代的解法么?

示例:

输入:{1,#,2,3}    输出:[3,2,1]

代码:

 1 /**
 2  * struct TreeNode {
 3  *    int val;
 4  *    struct TreeNode *left;
 5  *    struct TreeNode *right;
 6  * };
 7  */
 8 
 9 class Solution {
10 public:
11     /**
12      * 
13      * @param root TreeNode类 
14      * @return int整型vector
15      */
16     vector<int> postorderTraversal(TreeNode* root) {
17         vector<int> res;
18         if(root == NULL) return res;
19         stack<TreeNode*> st;
20         st.push(root);
21         while( !st.empty() ) {
22             TreeNode* temp = st.top();
23             st.pop();
24             res.push_back(temp->val);
25             if(temp->left != NULL)
26                 st.push(temp->left);
27             if(temp->right != NULL)
28                 st.push(temp->right);
29         }
30         reverse(res.begin(),res.end());
31         return res;
32     }
33 };

我的笔记:

  利用堆栈来实现后序遍历。

算法步骤:

  1. 存储根节点;
  2. 存取当前栈顶元素,并出栈;
  3. 分别判断左右结点是否为空;
  4. 依次放入左右结点;
  5. 再进行2~4操作直至栈中元素为空;
  6. 反转数组。
原文地址:https://www.cnblogs.com/john1015/p/13227471.html