LeetCode –Binary Tree Postorder Traversal

题目:

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

Example:

Input:

 [1,null,2,3] 1 \ 2 / 3

Output:

 [3,2,1]

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

 

解题:

       遍历顺序“根-左-右”

实现:

  • 使用栈实现
         从根节点开始,先将根节点压入栈,保存结果值,然后移动到右节点, 保证“根-右边”顺序, 为空后出栈,取其左节点入栈中。这样入栈就保证了访问顺序为“根-右-左”, 出栈实现“左-右-根”。
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
       vector<int> res;
       stack<TreeNode*> ss;
       TreeNode *p= root, *t;
        
       while(!ss.empty()||p){
           if (p){
               ss.push(p);
               res.insert(res.begin(), p->val);
               p = p->right;
           }
           else {
               p=ss.top();
               ss.pop();
               p= p->left;
               
           }
       }
       return res;
    }
};

实现:

  • 递归实现
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector <int> res;
        postorder(root, res);
        return res;
        
    }
    void postorder(TreeNode *root, vector<int> &res){
        if (!root) {
            return;
        }
        if (root->left) {
            postorder(root->left, res);
        }
        
        if (root->right){
            postorder(root->right, res);
        }
        res.push_back(root->val);
    }
};

参考:

[LeetCode] 145. Binary Tree Postorder Traversal 二叉树的后序遍历

 

Be First to Comment

发表回复