leetcode 145. 二叉树的后序遍历

 

 

方法1 递归解法:

左右根

代码

/**
 * 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>resut;
    vector<int> postorderTraversal(TreeNode* root) {
        transverse(root);
        return resut;

    }
    void transverse(TreeNode * node)
    {
        if (node!=NULL)
        {

            if (node->left!=NULL)
            {
                transverse(node->left);
            }
            if (node->right!=NULL)
            {
                transverse(node->right);
            }
            resut.push_back(node->val);
        }
    }
};/**
 * 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>resut;
    vector<int> postorderTraversal(TreeNode* root) {
        transverse(root);
        return resut;

    }
    void transverse(TreeNode * node)
    {
        if (node!=NULL)
        {

            if (node->left!=NULL)
            {
                transverse(node->left);
            }
            if (node->right!=NULL)
            {
                transverse(node->right);
            }
            resut.push_back(node->val);
        }
    }
};

方法2:迭代法

代码

/**
 * 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) {
        stack<TreeNode*>S;//定义栈存放右子树
        vector<int>resut;
        TreeNode*Rt = root;//迭代根节点
        while(Rt || S.size())
        {
            while(Rt)
            {
                //先序:根左右
                resut.push_back(Rt->val);//访问当前节点的值
                S.push(Rt->left);//将左子树保存到栈中
                Rt = Rt->right; //访问迭代节点的右子树
            }
            Rt = S.top();S.pop();//S栈顶元素出栈
        }
        reverse(resut.begin(),resut.end()); //翻转先序遍历的结果得到后序遍历的结果
        return resut;
    }
};

 

posted @ 2021-09-26 15:50  A-inspire  Views(31)  Comments(0Edit  收藏  举报