872. Leaf-Similar Trees

题目描述:

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.

解题思路:

DFS方法得到所有的叶子节点,得到叶子节点,判断就很简单了。

代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool leafSimilar(TreeNode* root1, TreeNode* root2) {
13         vector<int> leafs1;
14         vector<int> leafs2;
15         getLeaf(root1, leafs1);
16         getLeaf(root2, leafs2);
17         if (leafs1.size() != leafs2.size())
18             return false;
19         for (int i = 0; i < leafs1.size(); i++) {
20             if (leafs1[i] != leafs2[i])
21                 return false;
22         }
23         return true;
24     }
25     void getLeaf(TreeNode* root, vector<int>& leafs) {
26         if (root == NULL)
27             return;
28         getLeaf(root->left, leafs);
29         getLeaf(root->right, leafs);
30         if (root->left == NULL && root->right == NULL) {
31             leafs.push_back(root->val);
32         }
33         return;
34     }
35 };
原文地址:https://www.cnblogs.com/gsz-/p/9433587.html