Shopee笔试题
Shopee笔试
遍历二叉树
#include <iostream>
using namespace std;
struct Node{
int val;
Node* left;
Node* right;
}; //定义树的结点
void preorder(Node* node){ //先序遍历
if(node != NULL){
cout << node->val << " ";
preorder(node->left);
preorder(node->right);
}
}
void midorder(Node* node){
if(node!=NULL){
midorder(node->left);
cout << node->val << " ";
midorder(node->right);
}
}
void lastorder(Node* node){
if(node!=NULL){
lastorder(node->left);
lastorder(node->right);
cout << node->val << " ";
}
}
int main(){
//生成树方法1:暴力生成树的结点,然后依次使用指针连接起来
Node* a = new Node(); //a是结点1#的指针
Node* b = new Node(); //b是结点2#的指针
Node* c = new Node();
Node* d = new Node();
a->val = 5;
b->val = 6;
c->val = 7;
d->val = 8;
a->left =b;
a->right=c;
b->left =d;
b->right= NULL;
c->left = NULL;
c->right= NULL;
d->left = NULL;
d->right= NULL;
// 生成树方法2: BST(二叉搜索树)动态建立树的方法
preorder(a);
cout << endl;
midorder(a);
cout << endl;
lastorder(a);
cout << endl;
return 0;
}
生成(建立)二叉树之二叉搜索树
#include<iostream>
using namespace std;
struct Node{
int val;
Node* left;
Node* right;
};
struct Tree{
Node* root;
}; //这样可以把整个结点打包起来,一棵树只要保存根节点就OK
void insert(Tree* tree,int num){ //将结点插入到树中
//创造新结点
Node* p = new Node();
p->val = num;
p->left = NULL;
p->right= NULL;
if(tree->root == NULL){
tree->root = p; //新创造的节点插入到树上
}else{ //已经有根了
Node* temp = tree->root;
while(temp!=NULL){
if(num < temp->val){ //两种情况,一种是左边是空的;另一种是左边不为空
if(temp->left == NULL){
temp->left = node;
return 0;
}else{
temp = temp->left;
}
}else{
if(num < temp->val){ //还是两种情况,一种是右边是空直接插入;另一种是右边不是空继续右下移
if(temp->right == NULL){
temp->right = node;
return ;
}else{
temp = temp -> right;
}
}
}
}
}
}
int main(){
Tree tree;
tree.root = NULL;
int nums[7] = {3,5,2,6,8,1,4}
for(int i=0;i<7;i++){
insert(&tree,nums[i]);
}
return 0;
}