树(Tree)在数据结构还是很重要的,这里表示二叉树用括号表示法表示。
先写一个二叉树节点类:
// 二叉树节点
class BTNode {
public $data;
public $lchild = NULL;
public $rchild = NULL;
public function __construct($data) {
$this->data = $data;
}
}
然后构造二叉树:
function CreateBTNode(BTNode &$root = NULL, string $str)
{
$strArr = str_split($str);
$stack = [];
$p = NULL; // 指针
$top = -1;
$k = $j = 0;
$root = NULL;
foreach ($strArr as $ch) {
switch ($ch) {
case '(':
$top++;
array_push($stack, $p);
$k = 1;
break;
case ')':
array_pop($stack);
break;
case ',':
$k = 2;
break;
default:
$p = new BTNode($ch);
if($root == NULL) {
$root = $p;
} else {
switch ($k) {
case 1:
end($stack)->lchild = $p;
break;
case 2:
end($stack)->rchild = $p;
break;
}
}
break;
}
}
}
这里写上一个打印二叉树的函数(中序遍历):
function PrintBTNode($node)
{
if($node != NULL) {
PrintBTNode($node->lchild);
echo $node->data;
PrintBTNode($node->rchild);
}
}
运行结果:
输入一个字符串
"A(B(C,D),G(F))"
go语言实现
package main
import (
"fmt"
"strings"
)
type BinaryTreeNode struct {
data string
lChild *BinaryTreeNode
rChild *BinaryTreeNode
}
func CreateBinaryTree(sequence string) *BinaryTreeNode {
words := strings.Split(sequence, "")
stack := []*BinaryTreeNode{}
var p *BinaryTreeNode = nil
top := -1
k := 0
var root *BinaryTreeNode = nil
for _, word := range words {
switch word {
case "(":
top++
stack = append(stack, p)
k = 1
case ")":
stack = stack[0:top]
top--
k = 0
case ",":
k = 2
default:
p = &BinaryTreeNode{
word,
nil,
nil,
}
if root == nil {
root = p
} else {
endItem := stack[top]
switch k {
case 1:
endItem.lChild = p
case 2:
endItem.rChild = p
}
}
}
}
return root
}
// 中序遍历
func inOrderBinaryTree(root *BinaryTreeNode) {
if root != nil {
inOrderBinaryTree(root.lChild)
fmt.Print(root.data)
inOrderBinaryTree(root.rChild)
}
}
func main() {
testStr := "A(B(C,D),G(F))"
root := CreateBinaryTree(testStr)
inOrderBinaryTree(root)
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。