0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Leetcode 872. Leaf-Similar Trees

Posted at

872. Leaf-Similar Trees

難易度

Easy

アプローチ

DFS

/**
 * 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 ArrayList<Integer> arrayList1;
    public ArrayList<Integer> arrayList2;

    
    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        arrayList1 = new ArrayList<>();
        arrayList2 = new ArrayList<>();
        dfs1(root1);
        dfs2(root2);

        if (arrayList1.size() != arrayList2.size()) {
            return false;
        }

        for (int i = 0; i < arrayList1.size(); i++) {
            if (arrayList1.get(i).intValue() != arrayList2.get(i).intValue()) {
                return false;
            }
        }

        return true;
    }
    
    public  void dfs1(TreeNode root){
        if(root == null){
            return;
        }

        dfs1(root.left);
        dfs1(root.right);

        if(root.left == null && root.right == null){
            arrayList1.add(root.val);
        }
    }
    
    public  void dfs2(TreeNode root){
        if(root == null){
            return;
        }

        dfs2(root.left);
        dfs2(root.right);

        if(root.left == null && root.right == null){
            arrayList2.add(root.val);
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?