Leetcode 904 Solution

This article provides solution to leetcode question 904 (leaf-similar-trees)

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

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void get_leafs(TreeNode* root, vector<int>& ans) {
        if (root == NULL)
            return;

        if (root->left == NULL && root->right == NULL)
            ans.push_back(root->val);

        get_leafs(root->left, ans);
        get_leafs(root->right, ans);
    }

    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        vector<int> leafs1, leafs2;
        get_leafs(root1, leafs1);
        get_leafs(root2, leafs2);
        return leafs1 == leafs2;
    }
};