Skip to content

LeetCode: 872-Leaf-Similar Trees 解題紀錄

Last Updated on 2022-12-08 by Clay

題目

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.

Example 1:

Input: root1 = [3,5,1,6,2,9,8,null,null,7,4], root2 = [3,5,1,6,7,4,2,null,null,null,null,null,null,9,8]
Output: true

Example 2:

Input: root1 = [1,2,3], root2 = [1,3,2]
Output: false

Constraints:

  • The number of nodes in each tree will be in the range [1, 200].
  • Both of the given trees will have values in the range [0, 200].

題目會給定兩顆結構不同的樹,我們要判斷的是其葉子亦即不帶有子節點的節點)從左到右的序列是否一致。如果兩棵樹的葉子序列相同,返回 true;不同,則返回 false


解題思路

DFS

使用 DFS 走訪的話,便會理所當然地按照順序從左到右拜訪所有葉子節點。

我曾考慮過是否有一種先判斷第一棵樹 DFS 走到第一個葉子節點、接著再判斷第二顆樹 DFS 走到的一個葉子節點兩者是否相同,接著則是第一棵樹繼續往下走訪到第二個葉子節點... 依此類推。

但是考慮了一會兒似乎有點難寫,不確定是否有大神使用單線程寫出來了,照理來說應該可以... 但我還是首先採用暴力解了。

最直接的解法就是 DFS 走完兩顆樹,並在每一個節點時判斷底下是否有其他節點,若無,則使用一陣列將其保存起來;最後,則直接判斷兩棵樹的葉子節點陣列是否一致即可。


DFS 複雜度

Time ComplexityO(n)
Space ComplexityO(n)


C++ 範例程式碼

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void DFS(TreeNode* root, vector<int>& leaves) {
        // Base case
        if (!root) {
            return;
        }
        
        // If the root is a leaf
        if (!root->left && !root->right) {
            leaves.emplace_back(root->val);
        }

        // DFS
        DFS(root->left, leaves);
        DFS(root->right, leaves);
    }

    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        vector<int> leaves1;
        vector<int> leaves2;

        DFS(root1, leaves1);
        DFS(root2, leaves2);

        return leaves1 == leaves2;
    }
};



Python 範例程式碼

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def DFS(self, root: Optional[TreeNode], leaves: List[int]) -> None:
        # Base case
        if not root:
            return

        # If root is a leaf
        if not root.left and not root.right:
            leaves.append(root.val)

        self.DFS(root.left, leaves)
        self.DFS(root.right, leaves)

    
    def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
        v1 = []
        v2 = []

        self.DFS(root1, v1)
        self.DFS(root2, v2)

        return v1 == v2

References


Read More

Leave a Reply