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

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

解题思路:

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

 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=false;
17         
18         if(root2==null)
19             return false;
20         if(root1!=null && root2!=null)
21         {
22             if(root1.val==root2.val)
23                 result= istrue(root1,root2);
24             if(!result)
25                 result= istrue(root1.left,root2)||istrue(root1.right,root2);
26         }
27         return result;
28     }
29     
30     public boolean istrue(TreeNode node1,TreeNode node2)
31     {
32         if(node2==null)
33             return true;
34         if(node1==null)
35             return false;
36         if(node1.val!=node2.val)
37             return false;
38         return istrue(node1.left,node2.left)&&istrue(node1.right,node2.right);
39     }
40 }

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄