Skip to content

Latest commit

 

History

History
82 lines (67 loc) · 1.6 KB

572. Subtree of Another Tree.md

File metadata and controls

82 lines (67 loc) · 1.6 KB

Difficulty : Easy

Related Topics : Tree


Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.

Example 1:

Given tree s:

     3
    / \
   4   5
  / \
 1   2

Given tree t:

   4
  / \
 1   2

Return true, because t has the same structure and node values with a subtree of s.

Example 2:

Given tree s:

     3
    / \
   4   5
  / \
 1   2
    /
   0

Given tree t:

   4
  / \
 1   2

Return false.


Solution

  • mine
    • Java
      • Runtime: 5 ms, faster than 97.29%, Memory Usage: 39.4 MB, less than 6.39% of Java online submissions
        public boolean isSubtree(TreeNode s, TreeNode t) {
            if(t == null) return s == null;
            return dfs(s, t);
        }
        
        boolean dfs(TreeNode s, TreeNode t){
            if(s == null) return false;
        
            if(s.val == t.val && check(s, t)) return true;
            return dfs(s.left, t) || dfs(s.right, t);
        }
        
        boolean check(TreeNode s, TreeNode t){
            if(s == null) return t == null;
            if(t == null) return s == null;
        
            return s.val == t.val && check(s.left, t.left) && check(s.right, t.right);
        }