only the node with the same depth will be necessary to compare

// this is the best idea of using getDepth() here

only the getDepth() beside to get the max depth of the tree, another another to store all the tree node with the same depth of target tree of max depth

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<TreeNode> list = new ArrayList<>();
    public boolean isSubtree(TreeNode s, TreeNode t) {
        if (s == null && t == null) {
            return true;
        } 
        if(s == null || t == null) {
            return false;
        }

        getDepth(s, getDepth(t, -1));


        for(TreeNode node : list) {
            if(identical(node, t)) {
                return true;
            }
        }
        return false;
    }

    private int getDepth(TreeNode root, int d) {
        if (root == null) {
            return 0;
        }

        int left = getDepth(root.left, d);
        int right = getDepth(root.right, d);
        int maxDepth = Math.max(left, right) + 1;
        if (maxDepth == d) {
            list.add(root);
        }
        return maxDepth;
    }


    private boolean identical(TreeNode root, TreeNode target) {
        if (root == null && target == null) {
            return true;
        } 
        if (root == null || target == null || root.val != target.val) {
            return false;
        }


        return identical(root.left, target.left) && identical(root.right, target.right);
    }
}

results matching ""

    No results matching ""