树搜索 LeetCode-872 叶子相似的树
题目链接:LeetCode-872
题目大意:比较两个二叉树的叶子是否完全相同 包括顺序 1,2,3和1,3,2也算不相同哦
解题思路:创建两个集合 存储两个二叉树的叶子 之后搜索树的叶子就行了 搜到叶子将权值存进集合 最后将两个集合的元素进行比较
代码块:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
search(root1, list1);
search(root2, list2);
if(list1.size() != list2.size()) return false;
else{
for(int i=0;i<list1.size();i++){
if(list1.get(i) != list2.get(i)) return false;
}
}
return true;
}
public void search(TreeNode now, ArrayList<Integer> list){
if(now == null) return;
if(now.left == null && now.right == null) list.add(now.val);
else{
if(now.left != null){
search(now.left, list);
}
if(now.right != null){
search(now.right, list);
}
}
}
}