572.Subtree-of-Another-Tree

572. Subtree of Another Tree

题目地址

https://leetcode.com/problems/subtree-of-another-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.

代码

Approach 1:

class Solution {
    public boolean isSubtree(TreeNode s, TreeNode t) {
        String tree1 = preorder(s);
        String tree2 = preorder(t);
        return tree1.indexOf(tree2) >= 0;
    }

    private String preorder(TreeNode t) {
        if (t == null) return "null";
        return "#" + t.val + " " + preorder(t.left) + " " + preorder(t.right);
    }
}

Approach #2: By Comparison of Nodes

1、递归法自底向上Traverse

2、每层Traverse中,euqals当前节点值以及左右子节点是否相同

3、每层Traverse都会返回一个equals

Complexity Analysis

  • Time complexity :O(_mn). In worst case(skewed tree) traverse function takes _O(mn) time.

  • Space complexity : O(_n). The depth of the recursion tree can go upto n. _n refers to the number of nodes in s.

class Solution {
  public boolean isSubtree(TreeNode s, TreeNode t) {
    return traverse(s, t);
  }

  public boolean traverse(TreeNode s, TreeNode t) {
    return s != null && (equals(s, t) || traverse(s.left, t) || traverse(s.right, t));
  }

  public boolean equals(TreeNode x, TreeNode y) {
    if (x == null && y == null) return true;
    if (x == null || y == null) return false;

    return x.val == y.val 
      && equals(x.left, y.left) 
      && equals(x.right, y.right);
  }

}

Last updated