145 Binary Tree Postorder Traversal 二叉树的后序遍历

Posted lina2014

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了145 Binary Tree Postorder Traversal 二叉树的后序遍历相关的知识,希望对你有一定的参考价值。

给定一棵二叉树,返回其节点值的后序遍历。
例如:
给定二叉树 [1,null,2,3],
   1
    \
     2
    /
   3
返回 [3,2,1]。
注意: 递归方法很简单,你可以使用迭代方法来解决吗?
详见:https://leetcode.com/problems/binary-tree-postorder-traversal/description/

方法一:递归

/**
 * 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;
        if(root==nullptr)
        {
            return res;
        }
        return postorderTraversalHelper(root,res);
    }
    vector<int> postorderTraversalHelper(TreeNode* root,vector<int> &res)
    {
        if(root==nullptr)
        {
            return res;
        }
        postorderTraversalHelper(root->left,res);
        postorderTraversalHelper(root->right,res);
        res.push_back(root->val);
        return res;
    }
};

 方法二:非递归

/**
 * 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;
        if(root==nullptr)
        {
            return res;
        }
        stack<TreeNode*> stk1;
        stack<TreeNode*> stk2;
        stk1.push(root);
        while(!stk1.empty())
        {
            root=stk1.top();
            stk1.pop();
            stk2.push(root);
            if(root->left)
            {
                stk1.push(root->left);
            }
            if(root->right)
            {
                stk1.push(root->right);
            }
        }
        while(!stk2.empty())
        {
            root=stk2.top();
            stk2.pop();
            res.push_back(root->val);
        }
        return res;
    }
};

 

以上是关于145 Binary Tree Postorder Traversal 二叉树的后序遍历的主要内容,如果未能解决你的问题,请参考以下文章

145. Binary Tree Postorder Traversal

145. Binary Tree Postorder Traversal

145. Binary Tree Postorder Traversal

LeetCode145. Binary Tree Postorder Traversal 解题报告

LeetCode 145:Binary Tree Postorder Traversal

leetcode 145. Binary Tree Postorder Traversal