标签: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:
1
and 100
nodes.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呢?思考了一下,发现不可以。因为两个树的结构可能是不同的,无法在一个函数里保证都可以遍历到叶子节点。因此感觉没有办法直接比较实现。
标签:aws lis 节点 similar from amp 要求 nbsp arraylist
原文地址:https://www.cnblogs.com/boris1221/p/9751067.html