872.Leaf Similar Trees

872.Leaf Similar Trees

难度:Easy

请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。

举个例子,如上图所示,给定一颗叶值序列为 (6, 7, 4, 9, 8) 的树。

如果有两颗二叉树的叶值序列是相同,那么我们就认为它们是 叶相似 的。

如果给定的两个头结点分别为 root1 和 root2 的树是叶相似的,则返回 true;否则返回 false 。

提示: 给定的两颗树可能会有 1 到 100 个结点。

遍历叶子节点,然后判断顺序:

/**
 * 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 {
private:
    vector<int> r;
    string leaf(TreeNode* root)
    {
        string res;
        if(! root) return res;
        if(root->left)
            res+=leaf(root->left);
        if(root->right)
           res+=leaf(root->right);
       if(!root->left  && !root->right)
           res+= " "+ to_string(root->val);
        return res;
    }
public:
    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
   //    cout<< leaf(root1)<<endl;
     //    cout<< leaf(root2)<<endl;
        return leaf(root1) == leaf(root2);
    }
};

执行用时 : 16 ms, 在Leaf-Similar Trees的C++提交中击败了73.35% 的用户 内存消耗 : 14.5 MB, 在Leaf-Similar Trees的C++提交中击败了9.78% 的用户

Last updated