题目:输入两棵二叉树A和B,判断B是不是A的子结构。
代码中用到的二叉树源码:
http://blog.csdn.net/androiddevelop/article/details/18567085
/** * 面试题18 输入两棵二叉树A和B,判断B是不是A的子结构。 * * 2014-1-19 */ public class SubstructureInTree<T extends Comparable<? super T>> { public boolean hasSubtree(Node<T> root1, Node<T> root2) { boolean result = false; if (root1 != null && root2 != null) { if (root1.getData().compareTo(root2.getData()) == 0) { result = doesTree1HaveTree2(root1, root2); // System.out.println("value = " + result); } if (!result) { result = hasSubtree(root1.getLeftNode(), root2); } if (!result) { result = hasSubtree(root1.getRightNode(), root2); } } return result; } private boolean doesTree1HaveTree2(Node<T> root1, Node<T> root2) { if (root2 == null) { return true; } if (root1 == null) { return false; } if (root1.getData() != null && root2.getData() != null) { if (root1.getData().compareTo(root2.getData()) != 0) { return false; } } return doesTree1HaveTree2(root1.getLeftNode(), root2.getLeftNode()) && doesTree1HaveTree2(root1.getRightNode(), root2.getRightNode()); } public static void main(String[] args) { Integer[] data1 = {8, 8, 9, null, null, 2, 4, null, null, 7, null, null, 7, null, null}; BinaryTree<Integer> tree1 = new BinaryTree<Integer>(); tree1.createTree(data1); System.out.println("树A前序遍历"); tree1.preorderTraversal(tree1.getRootNode()); Integer[] data2 = {2, 4, null, null, 7, null, null}; BinaryTree<Integer> tree2 = new BinaryTree<Integer>(); tree2.createTree(data2); System.out.println("\n树B前序遍历"); tree2.preorderTraversal(tree2.getRootNode()); SubstructureInTree<Integer> inTree = new SubstructureInTree<Integer>(); boolean value = inTree.hasSubtree(tree1.getRootNode(), tree2.getRootNode()); System.out.println("\n" + value); } }
参考资料:
《剑指offer》面试题18