二叉树前序\中序\后序\层次遍历

节点信息

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) :val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

二叉树前中后序遍历递归版本

前序遍历

void preOrder(vector<int> &res, TreeNode *root) {
    if (root == nullptr) return;
    res.push_back(root->val);
    preOrder(res, root->left);
    preOrder(res, root->right);
}

中序遍历

void inOrder(vector<int> &res, TreeNode *root) {
    if (root == nullptr) return;
    inOrder(res, root->left);
    res.push_back(root->val);
    inOrder(res, root->right);
}

后序遍历

void postOrder(vector<int> &res, TreeNode *root) {
    if (root == nullptr) return;
    postOrder(res, root->left);
    postOrder(res, root->right);
    res.push_back(root->val);
}

二叉树前中后序遍历非递归版本

前序遍历

void preOrder(vector<int> &res, TreeNode *root) {
    if (root == nullptr) return;
    stack<TreeNode *> s;
    TreeNode *cur = root;
    s.push(cur);
    while (!s.empty()) {
        cur = s.top();
        s.pop;
        res.push_back(cur->val);
        if (cur->right) s.push(cur->right);
        if (cur->left) s.push(cur->left);
    }
}

中序遍历

void inOrder(vector<int> &res, TreeNode *root) {
    if (root == nullptr) return;
    stack<TreeNode *> s;
    TreeNode *cur = root;
    while (!s.empty() || cur != nullptr) {
        while (cur != nullptr) {
            s.push(cur);
            cur = cur->left;
        }
        TreeNode *tmp = s.top();
        s.pop();
        res.push_back(tmp->val);
        if (tmp->right) cur = tmp->right;
    }
}

后序遍历

先按照“根右左”遍历,最后在翻转成“左右根”

void postOrder(vector<int> &res, TreeNode *root) {
    if (root == nullptr) return;
    stack<TreeNode *> s;
    TreeNode *cur = root;
    s.push(cur);
    while (!s.empty()) {
        cur = s.top();
        s.pop();
        res.push_back(cur->val);
        if (cur->left) s.push(cur->left);
        if (cur->right) s.push(cur->right);
    }
    reverse(res.begin(), res.end());
}

二叉树层次遍历

//层次遍历
vector<vector<int>> levelOrder( TreeNode *root) {
    vector<vector<int>> res;
    if (root == nullptr) return res;
    queue<pair<TreeNode *, int>> q;
    TreeNode *cur = root;
    q.push(make_pair(cur, 0));
    while (!q.empty()) {
        pair<TreeNode *, int> tmp = q.front();
        q.pop();
        TreeNode *node = tmp.first;
        int level = tmp.second;
        if (level == res.size()) res.push_back(vector<int> ());
        res[level].push_back(node->val);
        if (node->left) q.push(make_pair(node->left, level + 1));
        if (node->right) q.push(make_pair(node->right, level + 1));
    }
    return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值