Created
April 6, 2022 12:31
-
-
Save esase/2f9cf880b884d4f2793831546d136db2 to your computer and use it in GitHub Desktop.
Same tree [https://leetcode.com/problems/same-tree]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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} p | |
* @param {TreeNode} q | |
* @return {boolean} | |
*/ | |
var isSameTree = function(p, q) { | |
const first = [] | |
const second = []; | |
getNodeValue(p, first); | |
getNodeValue(q, second); | |
if (first.length !== second.length) { | |
return false; | |
} | |
for (let i = 0; i < first.length; i++) { | |
if (first[i] !== second[i]) { | |
return false; | |
} | |
} | |
return true; | |
}; | |
var getNodeValue = function (node, res) { | |
if (!node) { | |
return; | |
} | |
res.push(node.val); | |
getNodeValue(node.left, res); | |
if (!node.left) { | |
res.push(null); | |
} | |
getNodeValue(node.right, res); | |
if (!node.right) { | |
res.push(null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment