leet-code/src/main/java/leetcode/editor/cn/LeafSimilarTrees.java

126 lines
3.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//请考虑一棵二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。
//
//
//
// 举个例子,如上图所示,给定一棵叶值序列为 (6, 7, 4, 9, 8) 的树。
//
// 如果有两棵二叉树的叶值序列是相同,那么我们就认为它们是 叶相似 的。
//
// 如果给定的两个根结点分别为 root1 和 root2 的树是叶相似的,则返回 true否则返回 false 。
//
//
//
// 示例 1
//
//
//
//
//输入root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,nul
//l,null,null,null,9,8]
//输出true
//
//
// 示例 2
//
//
//输入root1 = [1], root2 = [1]
//输出true
//
//
// 示例 3
//
//
//输入root1 = [1], root2 = [2]
//输出false
//
//
// 示例 4
//
//
//输入root1 = [1,2], root2 = [2,2]
//输出true
//
//
// 示例 5
//
//
//
//
//输入root1 = [1,2,3], root2 = [1,3,2]
//输出false
//
//
//
//
// 提示:
//
//
// 给定的两棵树可能会有 1 到 200 个结点。
// 给定的两棵树上的值介于 0 到 200 之间。
//
// Related Topics 树 深度优先搜索
// 👍 129 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.TreeNode;
import java.util.ArrayList;
import java.util.List;
//872:叶子相似的树
public class LeafSimilarTrees {
public static void main(String[] args) {
//测试代码
Solution solution = new LeafSimilarTrees().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
List<Integer> list1 = getLeaf(root1, new ArrayList<>());
List<Integer> list2 = getLeaf(root2, new ArrayList<>());
if (list1.size() != list2.size()) {
return false;
}
for (int i = 0; i < list1.size(); i++) {
if (!list1.get(i).equals(list2.get(i))) {
return false;
}
}
return true;
}
private List<Integer> getLeaf(TreeNode root, List<Integer> list) {
if (root.left == null && root.right == null) {
list.add(root.val);
return list;
}
if (root.left != null) {
list = getLeaf(root.left, list);
}
if (root.right != null) {
list = getLeaf(root.right, list);
}
return list;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}