日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【IT笔试面试题整理】判断一个树是否是另一个的子树

發布時間:2023/12/15 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【IT笔试面试题整理】判断一个树是否是另一个的子树 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

【試題描述】定義一個函數,輸入判斷一個樹是否是另一個對的子樹

You have two very large binary trees: T1, with millions of nodes, and T2, with hun-dreds of nodes Create an algorithm to decide if T2 is a subtree of T1

Note that the problem here specifies that T1 has millions of nodes—this means that we should be careful of how much space we use Let’s say, for example, T1 has 10 million nodes—this means that the data alone is about 40 mb We could create a string representing the inorder and preorder traversals If T2’s preorder traversal is a substring of T1’s preorder traversal, and T2’s inorder traversal is a substring of T1’s inorder traversal, then T2 is a sub-string of T1 We can check this using a suffix tree However, we may hit memory limitations because suffix trees are extremely memory intensive If this become an issue, we can use an alternative approach Alternative Approach: The treeMatch procedure visits each node in the small tree at most once and is called no more than once per node of the large tree Worst case runtime is at most O(n * m), where n and m are the sizes of trees T1 and T2, respectively If k is the number of occurrences of T2’s root in T1, the worst case runtime can be characterized as O(n + k * m)

【參考代碼】

1 boolean containsTree(Node t1, Node t2) 2 { 3 if (t2 == null) 4 return true; 5 else 6 return subTree(t1, t2); 7 } 8 9 boolean subTree(Node r1, Node r2) 10 { 11 if (r1 == null) 12 return false; 13 if (r1.value == r2.value) 14 { 15 if (matchTree(r1, r2)) 16 return true; 17 } 18 return (subTree(r1.left,r2) || subTree(r1.right,r2)); 19 } 20 21 boolean matchTree(Node r1, Node r2) 22 { 23 if (r2 == null && r1 == null) 24 return true; 25 if (r1 == null || r2 == null) 26 return false; 27 if (r1.value != r2.value) 28 return false; 29 return (matchTree(r1.left, r2.left) && matchTree(r1.right, r2.right)); 30 }

?

總結

以上是生活随笔為你收集整理的【IT笔试面试题整理】判断一个树是否是另一个的子树的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。