572.Subtree of Another Tree

Solution 1: DFS

https://leetcode.com/problems/subtree-of-another-tree/discuss/102724/
Time complexity : O(m*n)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSubtree(TreeNode s, TreeNode t) {
        if(s == null){
            return isSame(s, t);
        }
        else{
            if( isSame(s, t)){
                return true;
            }
            else{
                return isSubtree(s.left, t) || isSubtree(s.right, t);
            }
        }
    }
    //Judge if t1 is same with t2
    public boolean isSame(TreeNode t1, TreeNode t2){
        if(t1 == null && t2 == null){
            return true;
        }
        if(t1 == null || t2 == null){
            return false;
        }
        if(t1.val != t2.val){
            return false;
        }
        return isSame(t1.left, t2.left) && isSame(t1.right, t2.right);
    }
}

Solution 2

results matching ""

    No results matching ""