检测二叉树是否是另一个二叉树的子树

检测方法是先比较根节点,如果根节点相等继续比较左右子树,使用递归的方法;如果根节点不相等,则比较左子树的根节点是否和要比较的二叉树的根节点相等。

package binaryTree;

import java.util.regex.Matcher;

import javax.security.auth.Subject;

/** * 检测二叉树是否是另一个二叉树的子树 * * @author duola * */

public class hasSubTree {

    public static class BinaryTreeNode {
        BinaryTreeNode left;
        BinaryTreeNode right;
        int val;
    }

    private static boolean issubtree(BinaryTreeNode root1, BinaryTreeNode root2) {
        boolean flag = false;
        if (root2 == null)
            flag = true;
        if (root1 == null)
            flag = false;
        if (root1 != null && root2 != null) {
            if (root1.val == root2.val) {
                flag = doeshave(root1, root2);
            }
            if (!flag) {
                flag = issubtree(root1.left, root2);
            }
            if (!flag) {
                flag = issubtree(root1.right, root2);
            }
        }
        return flag;
    }

    private static boolean doeshave(BinaryTreeNode b1, BinaryTreeNode b2) {
        if (b2 == null)
            return true;
        if (b1 == null)
            return false;
        if (b1.val != b2.val)
            return false;
        if (b1.val == b2.val) {
            return doeshave(b1.left, b1.left) && doeshave(b1.right, b2.right);
        }
        return false;
    }

    public static void main(String [] args) {
        BinaryTreeNode root1=new BinaryTreeNode();
        BinaryTreeNode root2=new BinaryTreeNode();
    }




}

你可能感兴趣的:(递归,二叉树)