Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.html
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8)
.node
Two binary trees are considered leaf-similar if their leaf value sequence is the same.git
Return true
if and only if the two given trees with head nodes root1
and root2
are leaf-similar.github
这道题定义了一种叶类似树,就是说若两棵树的叶结点按照从左向右的顺序取出来排成序列,若两个序列相同,则说明两者是叶结点类似树。其实本质就是按从左到右的顺序打印二叉树的叶结点呗,那么根据这种顺序,咱们采用先序遍历遍历比较好,遇到叶结点后直接将叶结点存入数组中,那么对于两个树遍历后就分别获得两个包含叶结点的数组,最后再比较一下这两个数组是否相同便可,参见代码以下:数组
解法一:ide
class Solution { public: bool leafSimilar(TreeNode* root1, TreeNode* root2) { vector<int> leaf1, leaf2; helper(root1, leaf1); helper(root2, leaf2); return leaf1 == leaf2; } void helper(TreeNode* node, vector<int>& leaf) { if (!node) return; if (!node->left && !node->right) { leaf.push_back(node->val); } helper(node->left, leaf); helper(node->right, leaf); } };
咱们也能够不用数组,而是用两个字符串,那么在每一个叶结点值直接要加上一个分隔符,这样才能保证不会错位,最后比较两个字符串是否相等便可,参见代码以下:ui
解法二:code
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 同步地址:orm
https://github.com/grandyang/leetcode/issues/872htm
相似题目:
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