LeetCode 572. subtree to another tree (Subtree of Another Tree) 40

572. Another subtree tree
572. Subtree of Another Tree

Title Description
Given two nonempty binary s and t , test  s whether to include and t have the same structure and subtrees of the node values. s of a subtree including s all descendants of a node and the node. s can be seen as its own subtree.

Day algorithm 2019/6/12 Day 40 LeetCode 572. The Subtree of Another Tree

Example 1:
given tree s:

     3
    / \
   4   5
  / \
 1   2

Given a tree t:

   4 
  / \
 1   2

Return to true , because t to s a subtree and nodes have the same configuration values.

Example 2:
given tree s:

     3
    / \
   4   5
  / \
 1   2
    /
   0

Given a tree t:

   4
  / \
 1   2

Return false .

Java implementation
TreeNode Class

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 false;
        }
        if (isSame(s, t)) {
            return true;
        }
        return isSubtree(s.left, t) || isSubtree(s.right, t);
    }

    public boolean isSame(TreeNode s, TreeNode t) {
        if (s == null && t == null) {
            return true;
        }
        if (s == null || t == null) {
            return false;
        }
        if (s.val != t.val) {
            return false;
        }
        return isSame(s.left, t.left) && isSame(s.right, t.right);
    }
}

Similar topics

Reference material

Guess you like

Origin www.cnblogs.com/hglibin/p/11012726.html