The sword refers to the substructure of the Offer-Java-tree

tree substructure


Question:
Input two binary trees A and B, and determine whether B is a substructure of A. (ps: we agree that an empty tree is not a substructure of any tree)
code:

package com.sjsq.test;

/**
 * @author shuijianshiqing
 * @date 2020/5/19 20:47
 */

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

public class Solution {
    
    

    public boolean HasSubtree(TreeNode root1,TreeNode root2){
    
    
        boolean result = false;
        if(root1 != null && root2 != null){
    
    
            if(root1.val == root2.val){
    
    
                result = HasTree(root1,root2);
            }
            if(!result){
    
    
                result = HasTree(root1.left,root2);
            }
            if(!result){
    
    
                result = HasTree(root1.right,root2);
            }
        }
        return result;
    }

    public boolean HasTree(TreeNode root1,TreeNode root2){
    
    

        //首先是递归结束条件,递归到B没有子节点时,说明比较完了,B是A子结构
        //遍历到A没有子节点时,说明还有B的子孙节点没有比较,此时B不是A的结构
        //这两句的顺序不能颠倒,因为先判断的B树是否还有节点。
        if(root2 == null){
    
    
            return true;
        }
        if(root1 == null){
    
    
            return false;
        }
        if(root1.val != root2.val){
    
    
            return false;
        }

        //到这里说明传入的两颗树的根节点值相同
        return HasTree(root1.left,root2.left) && HasTree(root1.right,root2.right);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324211912&siteId=291194637