LeetCode 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].


用栈模拟递归过程, 后序要比其它两个遍历方式稍微复杂些, 要判断左右子节点都遍历后在访问根节点。


代码:

class Solution {
public:
    vector<int> postorderTraversal(TreeNode *root) {
        stack<TreeNode*> st;
        vector<int> ret;
        if(root == NULL)
            return ret;
        TreeNode* cur = NULL;
        TreeNode* pre = NULL;
        st.push(root);
        while(!st.empty())
        {
            cur = st.top();
            if((cur->left == NULL && cur->right == NULL) ||
               (pre != NULL && (cur->left == pre || cur->right == pre)))//如果是叶子节点或者是左右子孩子已经被访问过了,才能访问当前节点
            {
                ret.push_back(cur->val);
                st.pop();
                pre = cur;
            }
            else
            {
                if(cur->right != NULL)
                    st.push(cur->right);
                if(cur->left != NULL)
                    st.push(cur->left);
            }
        }
        return ret;
        
    }
};


你可能感兴趣的:(LeetCode,二叉树,遍历,traversal)