LeetCode题解:检查子树

检查子树

检查子树。你有两棵非常大的二叉树:T1,有几万个节点;T2,有几万个节点。设计一个算法,判断 T2 是否为 T1 的子树。

如果 T1 有这么一个节点 n,其子树与 T2 一模一样,则 T2 为 T1 的子树,也就是说,从节点 n 处把树砍断,得到的树与 T2 完全相同。

方法一:序列化

前序遍历,在遇到null节点时字符串添加空格,这样可唯一地确定一颗树,确定s2是否是s1的字串即可

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean checkSubTree(TreeNode t1, TreeNode t2) {
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 = new StringBuilder();
        bianli(s1, t1);
        bianli(s2, t2);
        return s1.toString().contains(s2);
    }

    public void bianli(StringBuilder str, TreeNode root){
        if (root == null){
            str.append(" ");
            return;
        }
        str.append(root.val);
        bianli(str, root.left);
        bianli(str, root.right);
    }
}

方法二:递归

挨个遍历节点,检查该节点的子树是否与t2匹配

	/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean checkSubTree(TreeNode t1, TreeNode t2) {
       if (t1 == null || t2 == null){
           return false;
       }
       return isEqual(t1, t2) || checkSubTree(t1.left, t2) || checkSubTree(t1.right, t2);
    }

    public boolean isEqual(TreeNode t1, TreeNode t2){
        if (t1 == t2) {
            return true;
        }
        if (t1 == null || t2 == null){
            return false;
        }
        return (t1.val == t2.val) && isEqual(t1.left, t2.left) && isEqual(t1.right, t2.right);
    }
}
上一篇:oracle update join


下一篇:ECCV2018 oral MVSNet 错误公式纠正及正确源代码推导解释