872. Leaf-Similar Trees

872. Leaf-Similar Trees

/**
 * 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 tree1 = new ArrayList();
      ArrayList tree2 = new ArrayList(); 
        traverse(root1, tree1);
        traverse(root2, tree2);
        
        if (tree1.size() != tree2.size()) return false;
        for (int i = 0; i < tree1.size(); i++){
            if (tree1.get(i) != tree2.get(i)) return false;
        }
        return true;
    }
public static void traverse (TreeNode root, ArrayList tree){
    
    if( root.right == null && root.left == null){
        tree.add(root.val);
        return;
    }
    if (root.right != null) traverse (root.right, tree);
    if (root.left != null) traverse (root.left, tree);
}    
    
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s