145.二叉树的后序遍历

在这里插入图片描述

迭代算法思路:
首先利用两个栈,一个为Stack,另一个为OutPut,开始时p指向整棵树的根节点,然后指针向右走,依次将节点压入两个栈中,当指针赋空时,从Stack中弹出一个节点赋给p,p再指向该节点的左子树。重复上述操作,直到Stack和p都为空。最后将OutPut中的元素依次弹出,即为二叉树的后序遍历。

/**
 * 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*> Stack,OutPut;
        vector<int> v;
        TreeNode* p=root;
        while(p||!Stack.empty())
        {
            while(p)
            {
                Stack.push(p);
                OutPut.push(p);
                p=p->right;
            }
            if(!Stack.empty())
            {
                p=Stack.top();
                Stack.pop();
                p=p->left;
            }
        }
        while(!OutPut.empty())
        {
            v.push_back(OutPut.top()->val);
            OutPut.pop();
        }
        return v;
    }
};

在这里插入图片描述

发布了90 篇原创文章 · 获赞 7 · 访问量 2178

猜你喜欢

转载自blog.csdn.net/weixin_43784305/article/details/103017396