Press "Enter" to skip to content

Posts tagged as “same tree”

花花酱 LeetCode 572. Subtree of Another Tree

Problem

题目大意:判断一棵树是不是另外一棵树的子树。

https://leetcode.com/problems/subtree-of-another-tree/description/

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:

Given tree t:

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

Example 2:
Given tree s:

Given tree t:

Return false.

Solution: Recursion

Time complexity: O(max(n, m))

Space complexity: O(max(n, m))

C++

Related Problems

 

花花酱 Leetcode 100. Same Tree

Problem:

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input:     1         1
          / \       / \
         2   3     2   3

        [1,2,3],   [1,2,3]

Output: true

Example 2:

Input:     1         1
          /           \
         2             2

        [1,2],     [1,null,2]

Output: false

Example 3:

Input:     1         1
          / \       / \
         2   1     1   2

        [1,2,1],   [1,1,2]

Output: false

 

Solution: Recursion

Time complexity: O(n)

Space complexity: O(n)

C++

Java

Python3

Follow Up