LeetCode872(2021.5.10)

LC872. 叶子相似的树

class Solution {
public:
    void dfs(TreeNode* node, vector<int>& seq) {
        if (!node->left && !node->right) seq.push_back(node->val);
        else {
            if (node->left) dfs(node->left, seq);
            if (node->right) dfs(node->right, seq);
        }
    }

    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        vector<int> seq1, seq2;
        if (root1) dfs(root1, seq1);
        if (root2) dfs(root2, seq2);
        return seq1 == seq2;
    }
};

发表评论