[leetcode] Leaf-Similar Trees
Posted Lin.B
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] Leaf-Similar Trees相关的知识,希望对你有一定的参考价值。
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
and100
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呢?思考了一下,发现不可以。因为两个树的结构可能是不同的,无法在一个函数里保证都可以遍历到叶子节点。因此感觉没有办法直接比较实现。
以上是关于[leetcode] Leaf-Similar Trees的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 872. Leaf-Similar Trees
Leetcode_easy872. Leaf-Similar Trees
Leetcode 872. Leaf-Similar Trees
[LeetCode] Leaf-Similar Trees 叶结点相似的树