LeetCode题目:二叉树的后序遍历

二叉树的后序遍历

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

示例:

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

输出: [3,2,1]

后序遍历比较复杂,但有种非常简单的方法:

	 把前序遍历反转  
	 如前序: root->left->right
	 修改前序: root->right->left
	 反转前序得到后序遍历:left->right->root
class Solution {
public:
    vector postorderTraversal(TreeNode* root) {
        vector res;
        if(root == NULL)
            return res;
        vector S;
        TreeNode* p = root;
        while(p!= NULL || !S.empty())
        {
            if( p!= NULL)
            {
                S.push_back(p);
                res.push_back(p->val);
                p = p->right;
            }
            else
            {
                p = S.back();
                S.pop_back();
                p = p->left;
            }
        }
        reverse(res.begin(), res.end());  
        return res;
    }
};

你可能感兴趣的:(LeetCode)