树的构建和遍历

LeetCode中树的构建和遍历

这里主要介绍如何给定N,构建一棵有N个节点的完全二叉树:

给定N,那么完全二叉树的结点值从1~N。我们可以使用层序遍历的方式为队列中的结点新建子节点,这里要注意子节点的值是否超过了给定的N。

代码

#include <bits/stdc++.h>

using namespace std;

struct Node
{
    int val;
    Node* left;
    Node* right;
    Node(int v)
    {
        val = v;
        left = nullptr;
        right = nullptr;
    }
};

Node* buildtree(int k)
{
    queue<Node*> q;
    Node* root = new Node(1);
    q.push(root);
    int cnt = 2;
    while(!q.empty())
    {
        Node* temp = q.front();
        q.pop();
        if(cnt <= k) {
            temp->left = new Node(cnt++);
            q.push(temp->left);
            if (cnt <= k) { //这里需要加上cnt的判断,以防没有右节点
                temp->right = new Node(cnt++);
                q.push(temp->right);
            }
        }
    }
    return root;
}

void preorder(Node* root)
{
    if(root == nullptr) return;
    cout << root->val << " ";
    if(root->left) preorder(root->left);
    if(root->right) preorder(root->right);
}

void inorder(Node* root)
{
    if(root == nullptr) return;
    if(root->left) preorder(root->left);
    cout << root->val << " ";
    if(root->right) preorder(root->right);
}

void postorder(Node* root)
{
    if(root == nullptr) return;
    if(root->left) preorder(root->left);
    if(root->right) preorder(root->right);
    cout << root->val << " ";
}

void levelorder(Node* root)
{
    queue<Node*> q;
    q.push(root);
    while(!q.empty())
    {
        Node* temp = q.front();
        q.pop();
        if(temp->left) q.push(temp->left);
        if(temp->right) q.push(temp->right);
        cout<< temp->val << " ";
    }
}

void dfs(Node* root)
{
    if(root == nullptr) return;
    dfs(root->left);
    dfs(root->right);
    cout << root->val << " ";
}

int main() {
    int k;
    cin >> k;
    Node* root = buildtree(k);

    //先序遍历
    cout << "preorder: ";
    preorder(root);
    cout<<endl;

    //中序遍历
    cout << "inorder: ";
    inorder(root);
    cout<<endl;

    //后序遍历
    cout << "postorder: ";
    postorder(root);
    cout<<endl;

    //层序遍历
    cout << "levelorder: ";
    levelorder(root);
    cout << endl;

    //dfs
    cout << "dfs: ";
    dfs(root);

    return 0;
}

上面给出了二叉树的先序遍历、中序遍历、后序遍历、层序遍历和dfs五种方式,刷题时会遇到。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值