From 8f333b266e606431c37c9ab96e4b9a97dd4ba8cc Mon Sep 17 00:00:00 2001 From: Jerry-306 <82520819+Jerry-306@users.noreply.github.com> Date: Sun, 26 Sep 2021 09:26:26 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20100=20=E7=9B=B8=E5=90=8C?= =?UTF-8?q?=E7=9A=84=E6=A0=91=E3=80=81257=20=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E6=89=80=E6=9C=89=E8=B7=AF=E5=BE=84=20=20=E4=B8=A4?= =?UTF-8?q?=E9=A2=98=E7=9A=84JavaScript=E7=89=88=E6=9C=AC=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 100 相同的树、257 二叉树的所有路径 两题的JavaScript版本代码 --- ...46\347\235\200\345\233\236\346\272\257.md" | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git "a/problems/\344\272\214\345\217\211\346\240\221\344\270\255\351\200\222\345\275\222\345\270\246\347\235\200\345\233\236\346\272\257.md" "b/problems/\344\272\214\345\217\211\346\240\221\344\270\255\351\200\222\345\275\222\345\270\246\347\235\200\345\233\236\346\272\257.md" index 7b0ccad77b..3c17e777c0 100644 --- "a/problems/\344\272\214\345\217\211\346\240\221\344\270\255\351\200\222\345\275\222\345\270\246\347\235\200\345\233\236\346\272\257.md" +++ "b/problems/\344\272\214\345\217\211\346\240\221\344\270\255\351\200\222\345\275\222\345\270\246\347\235\200\345\233\236\346\272\257.md" @@ -439,9 +439,84 @@ func traversal(root *TreeNode,result *[]string,path *[]int){ } ``` +JavaScript: +100.相同的树 +```javascript +/** + * 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) { + if (p === null && q === null) { + return true; + } else if (p === null || q === null) { + return false; + } else if (p.val !== q.val) { + return false; + } else { + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } +}; +``` + +257.二叉树的不同路径 +> 回溯法: +```javascript +/** + * 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} root + * @return {string[]} + */ +var binaryTreePaths = function(root) { + const getPath = (root, path, result) => { + path.push(root.val); + if (root.left === null && root.right === null) { + let n = path.length; + let str = ''; + for (let i=0; i'; + } + str += path[n-1]; + result.push(str); + } + + if (root.left !== null) { + getPath(root.left, path, result); + path.pop(); // 回溯 + } + + if (root.right !== null) { + getPath(root.right, path, result); + path.pop(); + } + } + + if (root === null) return []; + let result = []; + let path = []; + getPath(root, path, result); + return result; +}; +``` -----------------------