[LeetCode] 572. 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:
Given tree s:
3 / \ 4 5 / \ 1 2Given tree t:
4 / \ 1 2Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
Given tree s:
3 / \ 4 5 / \ 1 2 / 0Given tree t:
4 / \ 1 2Return false.
判斷 t 是否為 s 的子樹
思路: 先寫一個函數確定兩個樹 是相同的
https://leetcode.com/problems/same-tree/#/description
再來對樹 s 做遍歷 如果 找到一個 node 讓 s.val == t,val 就呼叫 上面的 isSameTree()
line 10 - 20: 寫一個 函數確定兩個樹 是相同的
line 24: 如果 s 或 t 有一個為空 那 t 絕對不會是 s 的子樹
line 25: 對樹 s 做遍歷 如果 找到一個 node 讓 s.val == t,val 就呼叫 上面的 isSameTree()
line 26 - 27: 對s 的左右子樹 遍歷
留言
張貼留言