您的位置:首页 > Web前端

剑指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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树