• LeetCode OJ--Binary Tree Postorder Traversal


    http://oj.leetcode.com/problems/binary-tree-postorder-traversal/

    树的后序遍历,可以使用递归,也可以使用栈,下面是栈的实现代码

    #include <iostream>
    #include <vector>
    #include <stack>
    using namespace std;
    
     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> ans;
            if(root == NULL)
                return ans;
            stack<TreeNode*> myStack;
            myStack.push(root);
            TreeNode* lastPop = NULL;
            TreeNode* nodeTop = NULL;
            while(!myStack.empty())
            {
                nodeTop = myStack.top();
                if(nodeTop->right && lastPop != nodeTop->right)
                    myStack.push(nodeTop->right);
                else if(nodeTop->right && lastPop == nodeTop->right)
                {
                    ans.push_back(nodeTop->val);
                    lastPop = nodeTop;
                    myStack.pop();
                    continue;
                }
                if(nodeTop->left && (nodeTop->right &&lastPop != nodeTop->right || nodeTop->right == NULL && lastPop != nodeTop->left))
                    myStack.push(nodeTop->left);
                else if(nodeTop->left && (nodeTop->right && lastPop == nodeTop->right || nodeTop->right == NULL && lastPop == nodeTop->left))
                {
                    ans.push_back(nodeTop->val);
                    lastPop = nodeTop;
                    myStack.pop();
                    continue;
                }
                if(nodeTop->left == NULL && nodeTop->right == NULL)
                {
                    ans.push_back(nodeTop->val);
                    lastPop = nodeTop;
                    myStack.pop();
                }
            }
            return ans;
        }
    };
    
    int main()
    { 
        TreeNode *root = new TreeNode(1);
        TreeNode *n2 = new TreeNode(2);
        //TreeNode *n3 = new TreeNode(2);
        TreeNode *n4 = new TreeNode(4);
        //TreeNode *n5 = new TreeNode(5);*/
        TreeNode *n6 = new TreeNode(3);
        TreeNode *n7 = new TreeNode(4);
    
        root->left = n2;
        //root->right = n3;
        n2->left = n4;
        //n2->right = n5;*/
        //n3->left = n6;
        //n6->right = n7;
        Solution myS;
        
        myS.postorderTraversal(root);
        return 0;
    }
  • 相关阅读:
    python处理excel文件
    Python datetime模块
    OrderedDict 有序字典以及读取json串时如何保持原有顺序
    ansible 学习笔记
    nginx的location和rewrite
    实体机重装系统
    热词
    教育
    生活
    1、两数之和
  • 原文地址:https://www.cnblogs.com/qingcheng/p/3550355.html
Copyright © 2020-2023  润新知