145. 二叉树的后序遍历 迭代 二叉树 栈

给定一个二叉树,返回它的 后序 遍历。

示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [3,2,1]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

迭代算法由144.二叉树的前序遍历演化而来,前序遍历为以根->左子树->右子树的顺序结合栈操作遍历,而后续则为根->右子树->左子树的倒序结合栈操作遍历。

/**
 * Definition for a binary tree node.
 * 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> res;
        stack<TreeNode*> stk;
        TreeNode* cur=root;
        while(cur||!stk.empty())
        {
            if(cur)
            {
                stk.push(cur);
                res.push_back(cur->val);
                cur=cur->right;
            }else
            {
                cur=stk.top()->left;
                stk.pop();
            }
        }
        reverse(res.begin(),res.end());
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/Wobushishenqiang/article/details/82385060