Leetcode(栈的题解)

Leetcode_20

括号匹配

#include 
#include 
#include 
using namespace std;
bool isValid(string s)
{
    stack stack;
    for(int i = 0;i

Leetcode_144

前序遍历

#include 
#include 
#include 
using namespace std;


struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x):val(x),left(NULL),right(NULL) {}
    
};
struct Command
{
    string s;
    TreeNode* node;
    Command(string s, TreeNode *node):s(s),node(node) {}
    
};


vector preorderTraversal(TreeNode* root)
{
    vector res;
    if(root==NULL)
        return res;

    stack stack;
    stack.push(Command("go",root));
    while(!stack.empty())
    {
        Command command = stack.top();
        stack.pop();
        if(command.s == "print")
            res.push_back(command.node->val);
        else{
            assert(command.s == "go");
            if(command.node->right)
                stack.push(Command("go",command.node->right));
            if(command.node->left)
                stack.push(Command("go",command.node->left));
            stack.push(Command("print",command.node));

        }

    }
    return res;
}

你可能感兴趣的:(Leetcode(栈的题解))