.Zzumbong

[leetCode/JS] 872. Leaf-Similar Trees ๋ณธ๋ฌธ

coding test/leetCode

[leetCode/JS] 872. Leaf-Similar Trees

์ญ˜๋ด‰ 2022. 12. 8. 09:20

๋‚œ์ด๋„ [ ๐Ÿ˜Š ] Easy

 

๋ฌธ์ œ ์„ค๋ช…

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.

 

2๊ฐœ์˜ 2์ง„ ํŠธ๋ฆฌ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํŠธ๋ฆฌ๋งˆ๋‹ค ๋งˆ์ง€๋ง‰ leaf ๊ฐ€ ์ˆœ์„œ์™€ ๊ฐ’์ด ๊ฐ™์„ ๋•Œ true๋ฅผ ๋„˜๊ธด๋‹ค.

 

์ž…์ถœ๋ ฅ ์˜ˆ

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].

 


 

๋‚ด ์†”๋ฃจ์…˜

  • ๋‹น์—ฐํžˆ ๊ธฐ๋ณธ์ ์ธ DFS ๋ฐฉ์‹์œผ๋กœ ํ’€์–ด์•ผํ•œ๋‹ค.
  • left, right๊ฐ€ ์กด์žฌํ•˜๋ฉด dfs()๋ฅผ ํ˜ธ์ถœํ•˜๊ณ  ๋‘˜๋‹ค ๊ฐ’์ด ์—†๋Š” ๋งˆ์ง€๋ง‰ Leaf ์ผ ๋•Œ, nodes์— `/${node.val}` ๋กœ ์ €์žฅํ•œ๋‹ค.
  • /๊ฐ€ ํ•„์š”ํ•œ ์ด์œ ๋Š” 1,2,3 ๊ณผ 12,3์ด ๊ฐ™์€ ๊ฐ’์ด ๋˜๊ธฐ ๋•Œ๋ฌธ.
var leafSimilar = function(root1, root2) {
  const getLastNode = (root) => {
    let nodes = '';
    const dfs = (node) => {
      if(node.left) dfs(node.left)
      if(node.right) dfs(node.right)
      if(!node.left && !node.right) nodes += `/${node.val}`
    }
    dfs(root);
    return nodes;
  }
  return getLastNode(root1) === getLastNode(root2);
};

 

๊ฐ์ƒํ‰

  • easy ๋ฌธ์ œ์ผ ์ˆ˜๋ก ๋‹ต์€ ํ•˜๋‚˜๋กœ ๊ท€๊ฒฐ๋  ์ˆ˜ ๋ฐ–์— ์—†๋‚˜๋ณด๋‹ค ๋‹ค๋ฅธ ์‚ฌ๋žŒ๋“ค์˜ ์†”๋ฃจ์…˜๋„ ๋น„์Šทํ•œ ๋ฐฉ์‹์ด๋‹ค.
  • ๋ฉ”๋ชจ๋ฆฌ๋Š” ์กฐ๊ธˆ ๋งŽ์ด ์‚ฌ์šฉํ–ˆ๋‹ค. ์™œ์ง€! ๋” ์ ์€ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•œ ์†”๋ฃจ์…˜์„ ๋ด๋„ ๋ฌด๊ฑฐ์›Œ๋ณด์ด๋Š”๋ฐ..
  • ํ•˜์ง€๋งŒ ๋นจ๋ž์ฃ ?

 

 

0 Comments
๋Œ“๊ธ€์“ฐ๊ธฐ ํผ