Brush Questions-Leetcode-Interview Questions 872. Trees with Similar Leaves (Deep Search)

872. Trees with Similar Leaves

Topic link

Source: LeetCode
Link: https://leetcode-cn.com/problems/leaf-similar-trees

Title description

Please consider all the leaves on a binary tree. The values ​​of these leaves are arranged from left to right to form a leaf value sequence.

For example, as shown in the figure above, given a tree whose leaf value sequence is (6, 7, 4, 9, 8).

If the leaf value sequences of two binary trees are the same, then we consider them to be leaf similar.

If the two trees whose head nodes are root1 and root2 are leaf-similar, return true; otherwise, return false.

Example 1:

Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null ,null,null,null,9,8]
Output: true
Example 2:

Input: root1 = [1], root2 = [1]
Output: true
Example 3:

Input: root1 = [1], root2 = [2]
Output: false
Example 4:

Input: root1 = [1,2], root2 = [2,2]
Output: true
Example 5:

Input: root1 = [1,2,3], root2 = [1,3,2]
Output: false

prompt:

A given two trees may have 1 to 200 nodes.
The values ​​on the given two trees are between 0 and 200.

Topic analysis

/**
 * 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:
    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
    
    
        vector<int> leaves1;
        vector<int> leaves2;
        dfs(root1,leaves1);
        dfs(root2,leaves2);

        return leaves1 == leaves2;
    }
    void dfs(TreeNode*root,vector<int> &leaves){
    
    
        if(root==NULL){
    
    
            return;
        }
        if(root->left==NULL && root->right==NULL){
    
    
            leaves.push_back(root->val);
        }
        dfs(root->left,leaves);
        dfs(root->right,leaves);
    }
};

Guess you like

Origin blog.csdn.net/qq_42771487/article/details/112985802