微信小程序中如何将一维数组按条件转换为二维数组?

微信小程序中如何将一维数组按条件转换为二维数组?,第1张

写个函数,也是来自于tp官方

function list_to_tree($list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {

// 创建Tree

$tree = array()

if(is_array($list)) {

// 创建基于主键的数组引用

$refer = array()

foreach ($list as $key =>$data) {

$refer[$data[$pk]] =&$list[$key]

}

foreach ($list as $key =>$data) {

// 判断是否存在parent

$parentId = $data[$pid]

if ($root == $parentId) {

$tree[] =&$list[$key]

}else{

if (isset($refer[$parentId])) {

$parent =&$refer[$parentId]

$parent[$child][] =&$list[$key]

}

}

}

}

return $tree

}

然后定义一维数组为$list,然后 print_r(list_to_tree($list,"id","parentsid","subnav"))

/*对于用户输入的任意一棵二叉树,仅使用一个指向二叉树T的根的指针,计算

(a)

T的节点数量

(b)

T的叶子数量

(c)

T的具有2个孩子的节点的数量

并分别计算其运行时间*/

#include<iostream>

#include<stdio.h>

#include<malloc.h>

int

TWOCHILD

//有两个孩子的结点

int

LEAF

//叶子数

int

NODE

//结点数

using

namespace

std

typedef

struct

binode{

int

data

struct

binode

*lchild,*rchild

}binode,*bitree

typedef

struct{

bitree

elem[100]

int

top

}stack

bitree

creat_bt(){

//按扩展前序建二叉树

bitree

tint

x

scanf("%d",&x)

if

(x==0)

t=NULL//以0作为结束

else

{

t=(bitree)malloc(sizeof(binode))

t->data=x

printf("请输入%d结点的左孩子结点(若没有,请输入

0)",t->data)

t->lchild=creat_bt()

printf("请输入%d结点的右孩子结点(若没有,请输入

0)",t->data)

t->rchild=creat_bt()

}

return

t

}

int

Twochild(bitree

t)

//先序递归统计有两孩子结点数

{

if(t)

{

if(t->lchild&&t->rchild)

TWOCHILD++

Twochild(t->lchild)

Twochild(t->rchild)

}

return

TWOCHILD

}

int

Leaf(bitree

t)

//先序递归统计叶子结点数

{

if(t)

{

if(!(t->lchild)&&!(t->rchild))

LEAF++

Leaf(t->lchild)

Leaf(t->rchild)

}

return

LEAF

}

int

Node(bitree

t)

//先序递归统计总结点数

{

if(t)

{

NODE++

Node(t->lchild)

Node(t->rchild)

}

return

NODE

}

__inline

unsigned

__int64

GetCycleCount()

//获取时间,纳秒级

{

__asm

_emit

0x0F

__asm

_emit

0x31

}

void

main()

{

TWOCHILD=LEAF=NODE=0

__int64

ls1,le1,ls2,le2,ls3,le3

printf("请输入您要新建的二叉树根结点:")

bitree

root=creat_bt()

ls1=GetCycleCount()

printf("\n该树中具有2个孩子的结点有%d个",Twochild(root))

le1=GetCycleCount()

printf("\n运行时间:%I64d

ns",(le1-ls1))

ls2=GetCycleCount()

printf("\n该树中叶子结点有%d个",Leaf(root))

le2=GetCycleCount()

printf("\n运行时间:%I64d

ns",(le2-ls2))

ls3=GetCycleCount()

printf("\n该树中结点有%d个",Node(root))

le3=GetCycleCount()

printf("\n运行时间:%I64d

ns\n",(le3-ls3))

system("pause")

}运行结果:


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/11352483.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-15
下一篇2023-05-15

发表评论

登录后才能评论

评论列表(0条)

    保存