剑指offer——树的子结构

题目链接:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

 

解题思路:

递归的方法,先判断根节点,如果相等,判断左子树以及右子树。

 1 /**
 2 public class TreeNode {
 3     int val = 0;
 4     TreeNode left = null;
 5     TreeNode right = null;
 6 
 7     public TreeNode(int val) {
 8         this.val = val;
 9 
10     }
11 
12 }
13 */
14 public class Solution {
15     public boolean HasSubtree(TreeNode root1,TreeNode root2) {
16         boolean result =true;
17         if(root2==null)
18             return false;
19         if(root1==null)
20             return false;
21         return isTree(root1,root2)||isTree(root1.left,root2)||isTree(root1.right,root2);
22     }
23     public boolean isTree(TreeNode root1,TreeNode root2)
24     {
25         if(root2==null)
26             return true;
27         if(root1==null)
28             return false;
29         if(root1.val!=root2.val)
30              return false;
31         return isTree(root1.left,root2.left)&&isTree(root1.right,root2.right);
32        
33     }
34     
35 }

 

posted @ 2019-05-14 08:27  王爷爱吃秋刀鱼  阅读(132)  评论(0编辑  收藏  举报