其他分享
首页 > 其他分享> > 【每日一题】872. 叶子相似的树

【每日一题】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);
        }
    }
}

标签:return,list1,872,list2,叶子,list,相似,addLeaf,root
来源: https://www.cnblogs.com/realzhaijiayu/p/14749927.html