欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

872. Leaf-Similar Trees

程序员文章站 2022-04-25 20:21:47
...

872. Leaf-Similar Trees


Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.

872. Leaf-Similar Trees

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.

Note:

Both of the given trees will have between 1 and 100 nodes.

方法1: recursion

思路:

遍历两棵树,序列化所有叶节点之后比较是否一致。

易错点

  1. 叶节点中间要用特殊符号拆开。

Complexity

Time complexity: O(T1 + T2)
Space complexity: O(T1 + T2)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool leafSimilar(TreeNode* root1, TreeNode* root2) {
        return leafHelper(root1, "") == leafHelper(root2, "");
    }
    
    string leafHelper(TreeNode* root, string t) {
        if (!root) return "";
        if (!root -> left && !root -> right) return to_string(root -> val) + "# ";
        return leafHelper(root -> left, t) + leafHelper(root -> right, t);
    }
};
相关标签: tree recursion