package main import ( "fmt" "goproject/src/node" ) /** 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构) 解:b树中找到a树的根节点,对比a树的每个节点与b树是否相同 */ func main() { d := node.SetNodeTree("D", nil, nil) c := node.SetNodeTree("C", &d, nil) b := node.SetNodeTree("B", nil, &c) h := node.SetNodeTree("H", nil, nil) k := node.SetNodeTree("K", nil, nil) g := node.SetNodeTree("G", &h, &k) f := node.SetNodeTree("F", &g, nil) e := node.SetNodeTree("E", nil, &f) a := node.SetNodeTree("A", &b, &e) is := isSubtree(&a,&f) fmt.Print(is) } func isSubtree(tree1 *node.NodeTree, tree2 *node.NodeTree) bool { if nil == tree1 { return false } if nil == tree2 { return false } rootnode := find(tree1,tree2) if nil == rootnode { return false } if nil == rootnode.Left && nil == rootnode.Right { return false } return equalsTree(rootnode,tree2) return false } /** 二叉查找 */ func find(tree *node.NodeTree, node *node.NodeTree) *node.NodeTree { if nil == tree || nil == node { return nil } current := tree if current.Data == node.Data { return current } else { //Leftfind Left := find(current.Left, node) if nil != Left { return Left } //Rightfind Right := find(current.Right, node) if nil != Right { return Right } return nil } } func equalsTree(tree *node.NodeTree,tree2 *node.NodeTree) bool { if nil == tree || nil == tree2 { return false } flag := tree.Data == tree2.Data if !flag { return false } //Left compare if nil != tree2.Left { return equalsTree(tree.Left,tree2.Left) } //Right compare if nil != tree2.Right { return equalsTree(tree.Right,tree2.Right) } return flag }
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
最新推荐文章于 2024-09-19 14:18:53 发布