【題目描述】
You have two every large binary trees:T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1.
Notice:A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.
有兩個(gè)不同大小的二叉樹:T1有上百萬的節(jié)點(diǎn);T2有好幾百的節(jié)點(diǎn)。請?jiān)O(shè)計(jì)一種算法,判定T2是否為T1的子樹。
【注】若 T1 中存在從節(jié)點(diǎn) n 開始的子樹與 T2 相同,我們稱 T2 是 T1 的子樹。也就是說,如果在 T1 節(jié)點(diǎn) n 處將樹砍斷,砍斷的部分將與 T2 完全相同。
【題目鏈接】
www.lintcode.com/en/problem/subtree/
【題目解析】
判斷 T2是否是 T1的子樹,首先應(yīng)該在 T1中找到 T2的根節(jié)點(diǎn),找到根節(jié)點(diǎn)后,兩棵子樹必須完全相同。所以整個(gè)思路分為兩步走:第一:找根節(jié)點(diǎn),第二:判斷兩棵樹是否全等。看起來很簡單,但實(shí)際實(shí)現(xiàn)時(shí)還是細(xì)致一點(diǎn),尤其要注意遞歸的先后順序、條件與&條件或的處理。
【參考答案】