mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加 100 相同的树、257 二叉树的所有路径 两题的JavaScript版本代码
添加 100 相同的树、257 二叉树的所有路径 两题的JavaScript版本代码
This commit is contained in:
@ -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;
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user