diff --git a/solution/0800-0899/0872.Leaf-Similar Trees/README.md b/solution/0800-0899/0872.Leaf-Similar Trees/README.md index 2baf6f3410c4c..9b8221fbc0d7d 100644 --- a/solution/0800-0899/0872.Leaf-Similar Trees/README.md +++ b/solution/0800-0899/0872.Leaf-Similar Trees/README.md @@ -224,6 +224,24 @@ impl Solution { } ``` +```js +var leafSimilar = function (root1, root2) { + const dfs = root => { + if (!root) { + return []; + } + let ans = [...dfs(root.left), ...dfs(root.right)]; + if (!ans.length) { + ans = [root.val]; + } + return ans; + }; + const l1 = dfs(root1); + const l2 = dfs(root2); + return l1.toString() === l2.toString(); +}; +``` + diff --git a/solution/0800-0899/0872.Leaf-Similar Trees/README_EN.md b/solution/0800-0899/0872.Leaf-Similar Trees/README_EN.md index 7c41bef49d159..3ebbc6f73c71b 100644 --- a/solution/0800-0899/0872.Leaf-Similar Trees/README_EN.md +++ b/solution/0800-0899/0872.Leaf-Similar Trees/README_EN.md @@ -214,6 +214,24 @@ impl Solution { } ``` +```js +var leafSimilar = function (root1, root2) { + const dfs = root => { + if (!root) { + return []; + } + let ans = [...dfs(root.left), ...dfs(root.right)]; + if (!ans.length) { + ans = [root.val]; + } + return ans; + }; + const l1 = dfs(root1); + const l2 = dfs(root2); + return l1.toString() === l2.toString(); +}; +``` + diff --git a/solution/0800-0899/0872.Leaf-Similar Trees/Solution.js b/solution/0800-0899/0872.Leaf-Similar Trees/Solution.js new file mode 100644 index 0000000000000..5f1ea802d15bd --- /dev/null +++ b/solution/0800-0899/0872.Leaf-Similar Trees/Solution.js @@ -0,0 +1,15 @@ +var leafSimilar = function (root1, root2) { + const dfs = root => { + if (!root) { + return []; + } + let ans = [...dfs(root.left), ...dfs(root.right)]; + if (!ans.length) { + ans = [root.val]; + } + return ans; + }; + const l1 = dfs(root1); + const l2 = dfs(root2); + return l1.toString() === l2.toString(); +};