2018年4月7日 星期六

[LeetCode] 572. Subtree of Another Tree

轉自LeetCode

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.

<Solution>

100. Same Tree 類似,但變成是要找 subRoot tree,需要點變化

想法如下
  • 這題直覺是要用遞迴解,因為過程中會需要返回上層再做一次檢查
  • 歷遍 tree s,把每個 node 都當作 root,去和 t 比對,看看是否相等。不相等,就繼續遞迴找
code 如下


Java

kotlin

沒有留言:

張貼留言