> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/872.leaf_similar_trees.md).

# 872.Leaf Similar Trees

**872.Leaf Similar Trees**

难度:Easy

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

![tree.png](https://i.loli.net/2019/04/30/5cc81134cc1e0.png)

举个例子，如上图所示，给定一颗叶值序列为 (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% 的用户


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://dfine.gitbook.io/leetcode/872.leaf_similar_trees.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
