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);
};
Top comments (0)