標籤: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