高质量代码-树的子结构

描述:输入两颗二叉树A,B,判断B是不是A的子结构。

思路:

没有难度,递归解决。关键是处理空指针。

解决:

 1 public class Solution {
 2     public boolean HasSubtree(TreeNode root1,TreeNode root2) {
 3         if (root1 == null || root2 == null) {
 4             return false;
 5         }
 6         return isSubTree(root1, root2);
 7     }
 8     
 9     boolean isSubTree(TreeNode root1, TreeNode root2) {
10         if (root2 == null) {
11             return true;
12         }
13         if (root1 == null && root2 != null) {
14             return false;
15         }
16         
17         if (root1.val != root2.val) {
18             return false;
19         } else if (isSubTree(root1.left, root2.left) && isSubTree(root1.right, root2.right)) {
20             return true;
21         } else {
22             return isSubTree(root1.left, root2) || isSubTree(root1.right, root2);
23         }
24     }
25     
26 }
原文地址:https://www.cnblogs.com/gatsbydhn/p/5347304.html