Leetcode刷题-2021-04-17

872. 叶子相似的树

能用LIst就不要用数组。
里面有很多函数,包括判断两个list是否相等,比自己写循环好多了
这是数组保存的结果,还有个测试样例不能过,本机上可以过

class Solution {
    int count;
    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        int[] leaf1=new int[100];
        int[] leaf2=new int[100];
        process(root1,leaf1);
        count=0;
        process(root2,leaf2);
        for(int i=0;i<count;i++){
            if(leaf1[i]==leaf2[i])
            continue;
            else 
            return false;
        }
        return true;
    }
     //求叶子序列
    public void process(TreeNode root,int[] leaf){
         if(root==null) return ;
         if(root.left==null && root.right==null) leaf[count++]=root.val;
         process(root.left,leaf);
         process(root.right,leaf);
    }
}

这是list,优点有不需要初始化,不需要固定尺寸大小,有封装好的equal函数不用进行for判断

class Solution {
    int count;
    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
         List<Integer> res1=new ArrayList<>();
         List<Integer> res2=new ArrayList<>();
         process(root1,res1);
         process(root2,res2);
         return res1.equals(res2);
    }
    //求叶子序列
    public static void process(TreeNode root,List<Integer> list){
         if(root==null) return ;
         if(root.left==null && root.right==null) list.add(root.val);
         process(root.left,list);
         process(root.right,list);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容