The sword refers to the substructure dfs of the tree

Ah, I haven't written a question for too long.

topic link

Find the root with equal vals on both sides, then dfs, remember to use && if the left-left and right-right are equal at the same time

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

 

Guess you like

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