樹(Tree)在數據結構仍是很重要的,這裏表示二叉樹用括號表示法表示。
先寫一個二叉樹節點類:node
// 二叉樹節點 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; } } }
這裏寫上一個打印二叉樹的函數(中序遍歷):app
function PrintBTNode($node) { if($node != NULL) { PrintBTNode($node->lchild); echo $node->data; PrintBTNode($node->rchild); } }
運行結果:
輸入一個字符串
"A(B(C,D),G(F))"
函數
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) }