添加 problem 572

This commit is contained in:
YDZ
2019-08-08 21:48:24 +08:00
parent c8a5f73493
commit d7be863e45
3 changed files with 136 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
package leetcode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isSubtree(s *TreeNode, t *TreeNode) bool {
if isSameTree(s, t) {
return true
}
if s == nil {
return false
}
if isSubtree(s.Left, t) || isSubtree(s.Right, t) {
return true
}
return false
}

View File

@@ -0,0 +1,61 @@
package leetcode
import (
"fmt"
"testing"
)
type question572 struct {
para572
ans572
}
// para 是参数
// one 代表第一个参数
type para572 struct {
s []int
t []int
}
// ans 是答案
// one 代表第一个答案
type ans572 struct {
one bool
}
func Test_Problem572(t *testing.T) {
qs := []question572{
question572{
para572{[]int{}, []int{}},
ans572{false},
},
question572{
para572{[]int{3, 4, 5, 1, 2}, []int{4, 1, 2}},
ans572{true},
},
question572{
para572{[]int{1, 1}, []int{1}},
ans572{true},
},
question572{
para572{[]int{1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, 2}, []int{1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, NULL, 1, 2}},
ans572{true},
},
}
fmt.Printf("------------------------Leetcode Problem 572------------------------\n")
for _, q := range qs {
_, p := q.ans572, q.para572
fmt.Printf("【input】:%v ", p)
roots := Ints2TreeNode(p.s)
roott := Ints2TreeNode(p.t)
fmt.Printf("【output】:%v \n", isSubtree(roots, roott))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,53 @@
# [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.
**Example 2:**Given tree s:
3
/ \
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return **false**.
## 题目大意
给定两个非空二叉树 s 和 t检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。
## 解题思路
- 给出 2 棵树 `s``t`,要求判断 `t` 是否是 `s` 的子树🌲。
- 这一题比较简单,针对 3 种情况依次递归判断,第一种情况 `s``t` 是完全一样的两棵树,第二种情况 `t``s` 左子树中的子树,第三种情况 `t``s` 右子树中的子树。第一种情况判断两棵数是否完全一致是第 100 题的原题。