[leetcode]872. Leaf-Similar Trees

[leetcode]872. Leaf-Similar Trees


Analysis

old friends~—— [嘻嘻~]

Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
直接把树的叶子节点提取出来,然后判断一下就好了~

Implement

/**
 * 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:
    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        vector leaf1, leaf2;
        leaves(root1, leaf1);
        leaves(root2, leaf2);
        if(leaf1 == leaf2)
            return true;
        return false;
    }
    void leaves(TreeNode* root, vector& leaf){
        if(!root)
            return ;
        else if(!root->left && !root->right)
            leaf.push_back(root->val);
        leaves(root->left, leaf);
        leaves(root->right, leaf);
    }
};

你可能感兴趣的:(LeetCode,tree)