99网
您的当前位置:首页872. Leaf-Similar Trees

872. Leaf-Similar Trees

来源:99网

Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.

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

Two binary trees are considered leaf-similar if their leaf value sequence is the same.

Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.

Note:

Both of the given trees will have between 1 and 100 nodes.

class Solution {
public:
    vector<int>seq1;
    vector<int>seq2;
    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        leafValueSequence(seq1,root1);
        leafValueSequence(seq2,root2);
        if(seq1.size()!=seq2.size()) return false;
        for(int i=0;i<seq1.size();i++)
            if(seq1[i]!=seq2[i])
                return false;
        return true;
    }
    void leafValueSequence(vector<int>& sequence,TreeNode* root)
    {//求root的叶子序列
        if(root)
        {
            if(!root->right&&!root->left)
            {
                sequence.push_back(root->val);
                return;
            }
            if(root->left) leafValueSequence(sequence,root->left);
            if(root->right) leafValueSequence(sequence,root->right);
        }
        
    }
};

因篇幅问题不能全部显示,请点此查看更多更全内容