剑指offer 18. 树的子结构

来源:互联网 发布:4g网络玩游戏延迟高 编辑:程序博客网 时间:2024/05/16 18:01
// 题目:给出两个树,判断B是否是A的子结构// 解法:递归的进行,转换每一个节点public class Main {public static void main(String[] args) {BinaryTreeNode root = new BinaryTreeNode();BinaryTreeNode n1 = new BinaryTreeNode();BinaryTreeNode n2 = new BinaryTreeNode();BinaryTreeNode n3 = new BinaryTreeNode();BinaryTreeNode n4 = new BinaryTreeNode();root.value = 50;n1.value = 25;n2.value = 75;n3.value = 10;n4.value = 35;root.leftNode = n1;root.rightNode = n2;n1.leftNode = n3;n1.rightNode = n4;System.out.println(hasSubTree(root, n1));System.out.println("complete!");}public static boolean hasSubTree(BinaryTreeNode root, BinaryTreeNode t) {if (root == null || t == null) {return false;}boolean result = false;if (root.value == t.value) {//如果一个结点的值相同就查两个树是否是子结构result = isSubTree(root, t);}if (!result) {//如果不等或不是子树,则开始遍历root树的左子树result = hasSubTree(root.leftNode, t);}if (!result) {//如果不等或不是子树,则开始遍历root树的右子树result = hasSubTree(root.rightNode, t);}return result;}public static boolean isSubTree(BinaryTreeNode a, BinaryTreeNode b) {if (b == null) {//如果b到了叶节点就返回truereturn true;}if (a == null) {//如果b不为叶节点,但a没有节点了,返回falsereturn false;}if (a.value != b.value) {//节点值不同就返回falsereturn false;}return isSubTree(a.leftNode, b.leftNode) && isSubTree(a.rightNode, b.rightNode);//继续查看两个树的左右结点}}

0 0