剑指Offer—17—树的子结构
2017-08-22 15:04
495 查看
树的子结构 : 输入两棵二叉树 A,B,判断 B 是不是 A 的子结构。(ps:我们约定空树不是任意一个树的子结构)
注意点:
异常情况
思路:
先找到相同的根节点,然后在判断他们的左右子树是否相同。
注意点:
异常情况
思路:
先找到相同的根节点,然后在判断他们的左右子树是否相同。
package A17树的子结构; public class Solution { public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public boolean HasSubtree(TreeNode root1, TreeNode root2) { // 先找到相同的根节点,然后在判断他们的左右子树是否相同。 boolean answer = false; if (root1 != null && root2 != null) { if (root1.val == root2.val) { answer = isTrue(root1, root2); } if (!answer) { answer = HasSubtree(root1.left, root2); } if (!answer) { answer = HasSubtree(root1.right, root2); } } return answer; } // 假设现在已经找到相同的根节点了 public boolean isTrue(TreeNode root1,TreeNode root2){ // 1 null 2 !null false // 1 != 2 false // 2 == null true if (root1 == null && root2 != null) { return false; } if (root1 != root2) { return false; } if (root2 == null) { return true; } return isTrue(root1.left, root2.left) && isTrue(root1.right, root2.right); } }
相关文章推荐
- 剑指offer--17树的子结构
- 牛客网-剑指offer-17-树的子结构
- 剑指offer_17_树的子结构
- 【剑指offer-解题系列(17)】树的子结构
- (C++)剑指offer-17:树的子结构(代码的鲁棒性)
- 剑指offer题解C++【17】树的子结构
- [剑指Offer] 17.树的子结构
- 剑指offer-17.树的子结构
- 【剑指offer】17树的子结构
- 剑指Offer-17-合并有序链表
- 剑指offer面试题18:树的子结构
- 【剑指offer】面试题26:树的子结构
- 剑指offer面试题17
- 剑指offer:树的子结构
- 剑指offer:树的子结构
- 剑指Offer之面试题18:树的子结构
- 剑指Offer 17 合并两个排序的链表
- 剑指offer 面试题18—树的子结构
- 剑指Offer-26:树的子结构
- 剑指Offer--面试题17:合并两个排序的链表--Java实现