[LeetCode] Binary Tree Postorder题解

Binary Tree Postorder

Given a binary tree, return the postorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

这是一道LeetCode中标记为Hard的题。事实上如果没有限定不使用递归的话,这道题是非常简单的。所以我只简单回顾一下这道题的两种解法:递归和迭代。

递归法实现后序遍历

算法复杂度为O(n)

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> re;
        print(root,re);
        return re;
    }
    void print(TreeNode *node,vector<int> &re){
        if(node == NULL) return;       
        print(node->left,re);//左    
        print(node->right,re);//右
        re.push_back(node->val);//中
    }
};

递归实现前序遍历和后序遍历,只要把print函数中“左右中”三行代码改成相应的顺序即可。

迭代实现后序遍历

迭代实现遍历的本质是广度优先搜索,思路如下:

  • Create an empty stack, Push root node to the stack.
  • Do following while stack is not empty.
  • pop an item from the stack and print it.
  • push the left child of popped item to stack.
  • push the right child of popped item to stack.
  • reverse the ouput.

其中,容易搞错的是输出“中”后,要先push左节点,再push右节点。因为对栈来说,先进去的左节点会后输出(先进后出,后进先出),就实现了“中右左”的顺序,再反转(reverse)就得到了后续遍历(左右中)。

算法复杂度为O(n)

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> re;
        stack<TreeNode*> visit;
        if(root != NULL) 
            visit.push(root);
        while(!visit.empty()){
            TreeNode *topNode = visit.top();
            visit.pop();//top方法只是获取最上面的元素,所以要用pop方法弹出
            re.push_back(topNode->val);
            if(topNode->left != NULL)
                visit.push(topNode->left);
            if(topNode->right != NULL)
                visit.push(topNode->right);
        }
        reverse(re.begin(),re.end());
        return re;
    }
};
posted @ 2017-09-10 15:21  liangf27  阅读(93)  评论(0编辑  收藏  举报