其他分享
首页 > 其他分享> > 【剑指OFFER】树的子结构

【剑指OFFER】树的子结构

作者:互联网

【问题描述】

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

 

【AC 代码】

Reference: https://blog.nowcoder.net/n/78f8183e6b8b40208483978b80cd8f74?f=comment

 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         if (root1 == null || root2 == null) return false;
17         return DoesTree1HasTree2(root1, root2) || HasSubtree(root1.left, root2) || HasSubtree(root1.right, root2);
18     }
19     private boolean DoesTree1HasTree2(TreeNode tree1, TreeNode tree2) {
20         if (tree2 == null) return true;
21         if (tree1 == null) return false;
22         if (tree1.val != tree2.val) return false;
23         return DoesTree1HasTree2(tree1.left, tree2.left) && DoesTree1HasTree2(tree1.right, tree2.right);
24     }
25 }
View Code

 

标签:return,val,OFFER,tree1,子结构,TreeNode,null,root2
来源: https://www.cnblogs.com/moongazer/p/11634584.html