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.
这道题定义了一种叶相似树,就是说若两棵树的叶结点按照从左向右的顺序取出来排成序列,若两个序列相同,则说明二者是叶结点相似树。其实本质就是按从左到右的顺序打印二叉树的叶结点呗,那么根据这种顺序,我们采用先序遍历遍历比较好,遇到叶结点后直接将叶结点存入数组中,那么对于两个树遍历后就分别得到两个包含叶结点的数组,最后再比较一下这两个数组是否相同即可,参见代码如下:
解法一:
class Solution {
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
vector leaf1, leaf2;
helper(root1, leaf1);
helper(root2, leaf2);
return leaf1 == leaf2;
}
void helper(TreeNode* node, vector& leaf) {
if (!node) return;
if (!node->left && !node->right) {
leaf.push_back(node->val);
}
helper(node->left, leaf);
helper(node->right, leaf);
}
};
我们也可以不用数组,而是用两个字符串,那么在每个叶结点值直接要加上一个分隔符,这样才能保证不会错位,最后比较两个字符串是否相等即可,参见代码如下:
解法二:
class Solution {
public:
bool leafSimilar(TreeNode* root1, TreeNode* root2) {
string leaf1, leaf2;
helper(root1, leaf1);
helper(root2, leaf2);
return leaf1 == leaf2;
}
void helper(TreeNode* node, string& leaf) {
if (!node) return;
if (!node->left && !node->right) {
leaf += to_string(node->val) + "-";
}
helper(node->left, leaf);
helper(node->right, leaf);
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/872
类似题目:
Binary Tree Preorder Traversal
参考资料:
https://leetcode.com/problems/leaf-similar-trees/
https://leetcode.com/problems/leaf-similar-trees/discuss/152329/C%2B%2BJavaPython-O(logN)-Space
https://leetcode.com/problems/leaf-similar-trees/discuss/152358/Simple-6-lines-Java-StringBuilder-%2B-traverse-with-explanation
LeetCode All in One 题目讲解汇总(持续更新中...)