首页 > 其他 > 详细

leet144 二叉树的前序遍历

时间:2020-11-08 22:24:59      阅读:31      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

 

/*
 * @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

 

leet144 二叉树的前序遍历

原文:https://www.cnblogs.com/yaodao12/p/13945498.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!