Skip to content

Commit

Permalink
Merge pull request #785 from Jerry-306/patch-18
Browse files Browse the repository at this point in the history
添加 100 相同的树、257 二叉树的所有路径  两题的JavaScript版本代码
  • Loading branch information
youngyangyang04 committed Sep 29, 2021
2 parents f8984e3 + 8f333b2 commit fd226ac
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions problems/二叉树中递归带着回溯.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<n-1; i++) {
str += path[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;
};
```


-----------------------
Expand Down

0 comments on commit fd226ac

Please sign in to comment.