美文网首页
leaf-similar-trees

leaf-similar-trees

作者: 小王同学加油 | 来源:发表于2019-03-22 17:03 被阅读0次

1 题目

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

image

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

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

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

提示:

  • 给定的两颗树可能会有 1100 个结点。
    英文:
    Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
t

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.

2测试

image.png
image.png

code

class Solution {
public:
     bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        vector<TreeNode*> a;
        vector<TreeNode*> b;
        dfs(root1,a);
        dfs(root2,b);
        int n=a.size();
        int m=b.size();
        if (n!=m)
        {
            return false;
        }
        
        for ( int i=0;i<n;i++)
        {
          if(a[i]->val !=b[i]->val )
          {
              return false;
          }
        }
        return true;
    }

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

    }
    
};

相关文章

  • 【1错-1】Leaf-Similar Trees

    https://leetcode.com/problems/leaf-similar-trees/ (图片来源ht...

  • leaf-similar-trees

    1 题目 中文:请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。 举个例子,如...

网友评论

      本文标题:leaf-similar-trees

      本文链接:https://www.haomeiwen.com/subject/ebdrvqtx.html