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:
Approach #2: By Comparison of Nodes
1、递归法自底向上Traverse
2、每层Traverse中,euqals当前节点值以及左右子节点是否相同
3、每层Traverse都会返回一个equals
Complexity Analysis
Time complexity :O(_m∗n). In worst case(skewed tree)
traversefunction takes _O(m∗n) time.Space complexity : O(_n). The depth of the recursion tree can go upto n. _n refers to the number of nodes in s.
Last updated
Was this helpful?