zoukankan      html  css  js  c++  java
  • leet144 二叉树的前序遍历

    /*
     * @lc app=leetcode.cn id=144 lang=cpp
     *
     * [144] 二叉树的前序遍历
     */
    
    // @lc code=start
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     * };
     */
    class Solution {
    public:
        // 递归版本
        // //因为要遍历所有节点, 所以 递归函数无返回值
        // vector<int> preorderTraversal(TreeNode* root) {
        //     if(root==nullptr) return {};
        //     vector<int> res;
        //     helper(root,res);
        //     return res;
        // }
        // void helper(TreeNode* root , vector<int>& res){
        //     if(root==nullptr) return ;
        //     res.push_back(root->val);
        //     helper(root->left, res);
        //     helper(root->right, res);
        // }
    
        // 迭代版本   使用stack  
        vector<int> preorderTraversal(TreeNode* root){
            if(root==nullptr) return {};
            vector<int> res;
            stack<TreeNode*> record;
            record.push(root);
            while(!record.empty()){
                TreeNode* tmp=record.top();
                record.pop();
                res.push_back(tmp->val);
                if(tmp->right) record.push(tmp->right);
                if(tmp->left) record.push(tmp->left);
            }
    
            return res;
        }
    };
    // @lc code=end
  • 相关阅读:
    JavaOne Online Hands-on Labs
    Using DTrace to Profile and Debug A C++ Program
    怎样挑选电线?家装用线越大越好吗?
    ORACLE DTRACE DOC
    内核书
    SQL Server vNext CTP 1.2
    用VS Code打造最佳Markdown编辑器
    opendtrace 开源汇总
    DTrace C++ Mysteries Solved 转
    MYSQL-RJWEB 博客学习
  • 原文地址:https://www.cnblogs.com/yaodao12/p/13945498.html
Copyright © 2011-2022 走看看