输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
1 package com.algorithm; 2 3 /*class TreeNode { 4 int val = 0; 5 TreeNode left = null; 6 TreeNode right = null; 7 public TreeNode(int val) { 8 this.val = val; 9 } 10 }*/ 11 public class HasSubtreeTest { 12 class TreeNode { 13 int val = 0; 14 TreeNode left = null; 15 TreeNode right = null; 16 17 public TreeNode(int val) { 18 this.val = val; 19 } 20 } 21 22 public boolean HasSubtree(TreeNode root1, TreeNode root2) { 23 boolean result = false;// 返回结果 24 if (root1 != null && root2 != null) { 25 if (root1.val == root2.val) 26 result = IsTree1HasTree2(root1, root2);// 递归遍历 27 if (!result) // 如果根结点不行,那么继续向左右子树遍历 28 result = IsTree1HasTree2(root1.left, root2); 29 if (!result) 30 result = IsTree1HasTree2(root1.right, root2); 31 } 32 return result; 33 } 34 35 public boolean IsTree1HasTree2(TreeNode root1, TreeNode root2) { 36 // 如果root1 为空 并且 root2不为空,那么代表并没有找到 37 if (root1 == null && root2 != null) 38 return false; 39 // 如果根2 为空 ,则代表当前结点有 40 if (root2 == null) 41 return true; 42 // 如果结点值不相等,那么返回false 43 if (root1.val != root2.val) 44 return false; 45 // 再左右遍历子树 46 return IsTree1HasTree2(root1.left, root2.left) 47 && IsTree1HasTree2(root1.right, root2.right); 48 } 49 50 public static void main(String[] args) { 51 52 } 53 }