题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
题解:递归
1 public static boolean HasSubtree(TreeNode root1,TreeNode root2) { 2 if(root1==null||root2==null){ 3 return false; 4 } 5 return tree1HasTree2(root1,root2)||HasSubtree(root1.left,root2)||HasSubtree(root1.right,root2); 6 } 7 public static boolean tree1HasTree2(TreeNode root1,TreeNode root2){ 8 if(root1==null){ 9 return false; 10 } 11 if(root2==null){ 12 return true; 13 } 14 return root1.val==root2.val&&tree1HasTree2(root1.left,root2.left) 15 &&tree1HasTree2(root1.right,root2.right); 16 }
初始化树:
1 public static class TreeNode { 2 int val = 0; 3 TreeNode left = null; 4 TreeNode right = null; 5 public TreeNode(int val) { 6 this.val = val; 7 } 8 } 9 private static List<TreeNode> nodeList = null; 10 public static TreeNode createBinTree(int[] array) { 11 nodeList=new LinkedList<TreeNode>(); 12 // 将一个数组的值依次转换为TreeNode节点 13 for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) { 14 nodeList.add(new TreeNode(array[nodeIndex])); 15 } 16 // 对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树 17 for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) { 18 // 左孩子 19 nodeList.get(parentIndex).left = nodeList.get(parentIndex * 2 + 1); 20 // 右孩子 21 nodeList.get(parentIndex).right = nodeList.get(parentIndex * 2 + 2); 22 } 23 // 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理 24 int lastParentIndex = array.length / 2 - 1; 25 // 左孩子 26 nodeList.get(lastParentIndex).left = nodeList.get(lastParentIndex * 2 + 1); 27 // 右孩子,如果数组的长度为奇数才建立右孩子 28 if (array.length % 2 == 1) { 29 nodeList.get(lastParentIndex).right = nodeList.get(lastParentIndex * 2 + 2); 30 } 31 return nodeList.get(0); 32 }
测试:
1 public static void main(String[] args) { 2 int[] tree1={8,8,7,9,2,-1,-1,-1,-1,4,7}; 3 int[] tree2={8,9,2}; 4 TreeNode root1 = createBinTree(tree1); 5 TreeNode root2 = createBinTree(tree2); 6 boolean hasSubtree = HasSubtree(root1, root2); 7 System.out.println(hasSubtree); 8 } 9 输出:true