LeetCode Daily Question 872. Trees with Similar Leaves

LeetCode Daily Question 872. Trees with Similar Leaves


Problem Description

insert image description here

Brief idea

For yesterday's daily question, I forgot to record and upload it for various reasons.
Simple questions, recursion of classic trees, two codes are two ways of writing, and should not be counted as two solutions. The three if conditions of writing method 2 are quite commonly used in the topic of trees.

the code

Writing 1:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    
    
public:
    void findLeaf(TreeNode* root, vector<int>& leaf){
    
    
        if(root == nullptr) return;
        if(root->left == nullptr && root->right == nullptr)
         leaf.push_back(root->val);
        findLeaf(root->left,leaf);
        findLeaf(root->right,leaf);
    }

    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
    
    
        vector<int> leaf1;
        vector<int> leaf2;
        findLeaf(root1,leaf1);
        findLeaf(root2,leaf2);
        return leaf1==leaf2;
    }
};
    }
};

Writing 2:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    
    
public:
    void findLeaf(TreeNode* root, vector<int>& leaf){
    
    
        if(root->left) findLeaf(root->left,leaf);
        if(root->left == nullptr && root->right == nullptr) leaf.push_back(root->val);
        if(root->right) findLeaf(root->right,leaf);
    }

    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
    
    
        vector<int> leaf1;
        vector<int> leaf2;
        findLeaf(root1,leaf1);
        findLeaf(root2,leaf2);
        return leaf1==leaf2;
    }
};

Guess you like

Origin blog.csdn.net/qq_45438600/article/details/116649754