diff --git a/problems/二叉树中递归带着回溯.md b/problems/二叉树中递归带着回溯.md index 7b0ccad7..3c17e777 100644 --- a/problems/二叉树中递归带着回溯.md +++ b/problems/二叉树中递归带着回溯.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; +}; +``` -----------------------