内容简介:给定两颗二叉树, 判断其叶子节点的序列是否是一致的.例:本题主要考察的是对树的遍历,遍历获取所有叶子节点,并比较是否一致即可。下面给出递归和非递归两种实现方式。
给定两颗二叉树, 判断其叶子节点的序列是否是一致的.
例:
树1: 4 / \ 2 7 / \ 1 3 叶子节点序列为 [1, 3, 7] 树2: 9 / \ 6 7 / \ 1 3 叶子节点序列为 [1, 3, 7] 两棵树叶子节点序列相同, 返回 true.
解法
本题主要考察的是对树的遍历,遍历获取所有叶子节点,并比较是否一致即可。下面给出递归和非递归两种实现方式。
递归写法 (DFS):
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean leafSimilar(TreeNode root1, TreeNode root2) { ArrayList<Integer> list1 = new ArrayList<>(); ArrayList<Integer> list2 = new ArrayList<>(); dfs(root1, list1); dfs(root2, list2); return list1.equals(list2); } private void dfs(TreeNode root, ArrayList<Integer> list) { if (root == null) { return; } if (root.left == null && root.right == null) { list.add(root.val); } dfs(root.left, list); dfs(root.right, list); } }
Runtime: 0 ms, faster than 100.00% of Java online submissions for Leaf-Similar Trees. Memory Usage: 37.3 MB, less than 6.16% of Java online submissions for Leaf-Similar Trees.
非递归写法:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution2 { public boolean leafSimilar(TreeNode root1, TreeNode root2) { ArrayList<Integer> list1 = new ArrayList<>(); ArrayList<Integer> list2 = new ArrayList<>(); pushLeafRoot(root1, list1); pushLeafRoot(root2, list2); return list1.equals(list2); } private void pushLeafRoot(TreeNode root, ArrayList<Integer> list) { if (root == null) { return; } Stack<TreeNode> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()) { TreeNode node = stack.pop(); if (node.left != null) { stack.push(node.left); } if (node.right != null) { stack.push(node.right); } if (node.left == null && node.right == null) { list.add(node.val); } } } }
Runtime: 1 ms, faster than 82.41% of Java online submissions for Leaf-Similar Trees. Memory Usage: 36.7 MB, less than 71.02% of Java online submissions for Leaf-Similar Trees.
以上所述就是小编给大家介绍的《LeetCode 872 Leaf-Similar Trees》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。