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五种方式,刷题时会遇到。