树的子结构

来源:互联网 发布:linux c 守护进程 编辑:程序博客网 时间:2024/05/17 00:07

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

思路1:直接遍历两棵树返回序列,判断序列是否是子序列

思路2:比较AB根节点,如果不同,再递归比较A的左子树右子树和B

/**public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}*/public class Solution {    public boolean HasSubtree(TreeNode root1,TreeNode root2) {        if(root1==null || root2==null)            return false;        return visit(root1).contains(visit(root2));    }    public String visit(TreeNode root){        if(root==null)return "";        StringBuffer sb=new StringBuffer();        sb.append(root.val);        sb.append(visit(root.left));        sb.append(visit(root.right));        return sb.toString();    }}


思路2

public class Solution {    public boolean HasSubtree(TreeNode root1,TreeNode root2) {        if (root1 == null || root2 == null) return false;        return isSubTree(root1, root2) || HasSubtree(root1.left, root2) ||  HasSubtree(root1.right, root2);    }  public boolean isSubTree(TreeNode pRootA, TreeNode pRootB){        if (pRootB == null) return true;        if (pRootA == null) return false;        if (pRootB.val == pRootA.val) {            return isSubTree(pRootA.left, pRootB.left) && isSubTree(pRootA.right, pRootB.right);        } else             return false;    }}


0 0