力扣144——二叉树的前序遍历

 递归先序遍历

/**
 * 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) {
        vector<int>vec;
        preorder(root,vec);
        return vec;
    }
    void preorder(TreeNode* &root,vector<int> &vec){
        if(root==nullptr)return;
        vec.push_back(root->val);
        preorder(root->left,vec);
        preorder(root->right,vec);
    }
};

非递归前序遍历:

思路:
        1、首先申请一个新的栈,记为stk.
        2、然后将头节点root压入stk中。
        3、每次从stk中弹出栈顶节点,记为cur ,然后打印cur节点的值。如果cur右孩子不为空的话,将cur的右孩子先压入stk中。最后如果cur的左孩子不为空的话,将cur的左孩子压入stack中。
        4、不断重复步骤3 ,直到stk为空,全部过程结束。

代码:

/**
 * 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>vec;
        stack<TreeNode*>stk;
        stk.push(root);
        while(!stk.empty()){
            TreeNode* cur=stk.top();
            stk.pop();
            vec.push_back(cur->val);
            if(cur->right) stk.push(cur->right);
            if(cur->left) stk.push(cur->left);
        }
        return vec;
    }
};

时间复杂度均为:O(n)

空间复杂度均为:O(n)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值