【每日一题】872. 叶子相似的树

https://leetcode-cn.com/problems/leaf-similar-trees/

class Solution {
    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();

        addLeaf(root1, list1);
        addLeaf(root2, list2);

        if(list1.size() != list2.size()){
            return false;
        }
        for(int i = 0; i < list1.size(); i++){
            if(list1.get(i) != list2.get(i)){
                return false;
            }
        }
        return true;
    }

    //后序遍历
    public void addLeaf(TreeNode root, List<Integer> list){
        if(root == null){
            return ;
        }
        addLeaf(root.left, list);
        addLeaf(root.right, list);
        if(root.left == null && root.right == null){
            list.add(root.val);
        }
    }
}
上一篇:Python列表赋值拷贝,浅拷贝,深拷贝的区别!


下一篇:代码