[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 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呢?思考了一下,发现不可以。因为两个树的结构可能是不同的,无法在一个函数里保证都可以遍历到叶子节点。因此感觉没有办法直接比较实现。

猜你喜欢

转载自www.cnblogs.com/boris1221/p/9751067.html