LeetCode: Binary Tree Postorder Traversal [145]

【题目】

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?


【题意】

    非递归实现后续遍历


【思路】

    维护两个栈,一个栈用来存储标记,标记相应的结点的右子树是否已经被遍历;另一个栈存储树节点,用以模拟后序遍历。


【代码】

/**
 * Definition for binary tree
 * 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>result;
        TreeNode*node=root;
        stack<TreeNode*>st;
        stack<bool>st_flag;
        
        while(node){
            st.push(node);
            st_flag.push(false);
            node=node->left;
        }
        while(!st.empty()){
            bool status = st_flag.top();
            if(!status){
                //访问右子树
                st_flag.pop(); st_flag.push(true);
                node = st.top();
                node=node->right;
                while(node){
                    st.push(node);
                    st_flag.push(false);
                    node=node->left;
                }
            }
            else{
                //访问当前结点
                st_flag.pop();
                node = st.top(); st.pop();
                result.push_back(node->val);
            }
        }
        return result;
    }
};


你可能感兴趣的:(LeetCode,算法,面试)