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<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);
}
};
我們也可以不用數組,而是用兩個字符串,那么在每個葉結點值直接要加上一個分隔符,這樣才能保證不會錯位,最后比較兩個字符串是否相等即可,參見代碼如下:
解法二:
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
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)