当前位置: 首页 > 后端技术 > PHP

二叉树算法的构建

时间:2023-03-29 21:52:20 PHP

树(Tree)在数据结构中还是很重要的,这里指的是二叉树用括号表示法表示。先写一个二叉树节点类://二叉树节点类BTNode{public$data;公共$lchild=NULL;公共$rchild=NULL;公共函数__construct($data){$this->data=$data;}}然后构建二叉树:functionCreateBTNode(BTNode&$root=NULL,string$str){$strArr=str_split($str);$堆栈=[];$p=空;//指针$top=-1;$k=$j=0;$root=NULL;foreach($strArras$ch){switch($ch){case'(':$top++;array_push($stack,$p);$k=1;break;case')':array_pop($stack);}休息;案例',':$k=2;休息;默认值:$p=newBTNode($ch);如果($root==NULL){$root=$p;}else{switch($k){案例1:end($stack)->lchild=$p;休息;情况2:end($stack)->rchild=$p;休息;}}休息;}}}这是一个打印二叉树的函数(中序遍历):回声$节点->数据;PrintBTNode($node->rchild);}}运行结果:输入一个String"A(B(C,D),G(F))"Go语言实现包mainimport("fmt""strings")typeBinaryTreeNodestruct{datastringlChild*BinaryTreeNoderChild*BinaryTreeNode}funcCreateBinaryTree(sequencestring)*BinaryTreeNode{words:=strings.Split(sequence,"")stack:=[]*BinaryTreeNode{}varp*BinaryTreeNode=niltop:=-1k:=0varroot*BinaryTreeNode=nilfor_,word:=rangewords{switchword{case"(":top++stack=append(stack,p)复制代码k=1case")":stack=stack[0:top]top--k=0case",":k=2default:p=&BinaryTreeNode{word,nil,nil,}ifroot==nil{根=p}else{endItem:=stack[top]switchk{case1:endItem.lChild=pcase2:endItem.rChild=p}}}}returnroot}//中序遍历funcinOrderBinaryTree(root*BinaryTreeNode){ifroot!=nil{inOrderBinaryTree(root.lChild)fmt.Print(root.data)inOrderBinaryTree(root.rChild)}}funcmain(){testStr:="A(B(C,D),G(F))"root:=CreateBinaryTree(testStr)inOrderBinaryTree(root)}