DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Leaf-Similar Trees

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.

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

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root1
 * @param {TreeNode} root2
 * @return {boolean}
 */
var leafSimilar = function (root1, root2) {
  let resultRoot1 = [];
  let resultRoot2 = [];
  getNodes(root1, resultRoot1);
  getNodes(root2, resultRoot2);

  let isValid = false;

  if (resultRoot1.length !== resultRoot2.length) {
    return false;
  }

  for (let i = 0; i < resultRoot1.length; i++) {
    if (resultRoot1[i] !== resultRoot2[i]) {
      return false;
    }
  }
  return true;
};

const getNodes = (root, result) => {
  if (root === null) {
    return;
  }
  if (root.left === null && root.right === null) {
    result.push(root.val);
  }
  getNodes(root.left, result);
  getNodes(root.right, result);
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Visualizing Promises and Async/Await ๐Ÿคฏ

async await

โ˜๏ธ Check out this all-time classic DEV post