[leetcode] Leaf-Similar Trees

來源:互聯網
上載者:User

標籤:aws   lis   節點   similar   from   amp   要求   nbsp   arraylist   

Consider all the leaves of a binary tree.  From left to right order, the values of those leaves form a leaf value sequence.

For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Note:

  • Both of the given trees will have between 1 and 100 nodes.
分析:題目翻譯一下:給定兩顆二叉樹,要求判斷兩個二叉樹的葉子節點值是否相同。思路一:因為要判斷兩個二叉樹葉子節點值,因此只要用兩個list儲存每個二叉樹葉子節點值,然後比較是否相等就可以了。在尋找每個二叉樹葉子節點的時候使用DFS搜尋。代碼如下:
 1 class Solution { 2     List<Integer> list1 = new ArrayList<>(); 3     List<Integer> list2 = new ArrayList<>(); 4     public boolean leafSimilar(TreeNode root1, TreeNode root2) { 5         helper(root1,list1); 6         helper(root2,list2); 7         return list1.equals(list2); 8     } 9     private void helper(TreeNode root, List<Integer> list) {10         if ( root == null ) return;11         if ( root.left == null && root.right == null ) list.add(root.val);12         helper(root.left,list);13         helper(root.right,list);14     }15 }

    已耗用時間3ms,擊敗71.4%。看了一下最快的答案也是這種思路。

其實這個思路還可以變一下,只是用一個list。首先用list儲存root1上的葉子節點,然後在遍曆root2樹的時候,如果相等就依次從list中刪除,最後判斷是否為空白。要寫兩個函數,也比較繁瑣了。

第二個思路:那麼是否可以不適用list呢?思考了一下,發現不可以。因為兩個樹的結構可能是不同的,無法在一個函數裡保證都可以遍曆到葉子節點。因此感覺沒有辦法直接比較實現。

[leetcode] Leaf-Similar Trees

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.