872. Leaf-Similar Trees

迷南。 2022-04-22 21:34 201阅读 0赞

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

  1. ![tree.png][]

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.

    /**

    • 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) {
      1. vector<int> res1 = GetSeq(root1);
      2. vector<int> res2 = GetSeq(root2);
      3. if(res1.size()!= res2.size())
      4. return false;
      5. for(int i = 0; i<res1.size(); i++)
      6. {
      7. if(res1[i]!= res2[i])
      8. return false;
      9. }
      10. return true;
      }

    private:
    vector GetSeq(TreeNode* root)

    1. {
    2. vector<int> result;
    3. if(root == NULL)
    4. return result;
    5. stack<TreeNode*> stackNode;
    6. while(root!=NULL || !stackNode.empty())
    7. {
    8. while(root)
    9. {
    10. if(root->left == NULL && root->right == NULL)
    11. {
    12. result.push_back(root->val);
    13. }
    14. stackNode.push(root);
    15. root = root->left;
    16. }
    17. TreeNode* temp = stackNode.top();
    18. stackNode.pop();
    19. root = temp->right;
    20. }
    21. return result;
    22. }

    };

发表评论

表情:
评论列表 (有 0 条评论,201人围观)

还没有评论,来说两句吧...

相关阅读

    相关 NYOJ 872 开会

    开会 时间限制: 1000 ms | 内存限制: 65535 KB 难度: 0 描述 在南阳理工学院,经常会在小礼堂举办活动、开大型会议,多数情况下都是从每个班里抽

    相关 leetcode 872. 叶子相似的树

    请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。 ![tree.png][] 举个例子,如上图所示,给定一颗叶值序列为 `(6, 7,