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