问题描述: 判断树A是否是树B的子结构。
解法与分析: 使用递归的方式很容易解决。先进行根结点比较,相等的话,递归左右子树。
参考代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| public static boolean isIncludeTree(TreeNode parent, TreeNode child) { boolean result = false; if (parent == null || child == null) { return result; } if (parent.value==child.value) { result = hasTree(parent, child); } if (!result) { result = isIncludeTree(parent.left, child); } if (!result) { result = isIncludeTree(parent.right, child); }
return result; }
private static boolean hasTree(TreeNode parent, TreeNode child) { if (child == null) { return true; } if (parent == null||parent.value!=child.value) { return false; }
return hasTree(parent.left, child.left) && hasTree(parent.right, child.right); }
|