Merge pull request #1695 from L1Y1/master

Update 0235.二叉搜索树的最近公共祖先.md
This commit is contained in:
程序员Carl
2022-10-20 09:18:34 +08:00
committed by GitHub
2 changed files with 23 additions and 18 deletions

View File

@ -416,24 +416,31 @@ func backTree(n,k,startIndex int,track *[]int,result *[][]int){
* @return {number[][]}
*/
var combinationSum3 = function(k, n) {
const backtrack = (start) => {
const l = path.length;
if (l === k) {
const sum = path.reduce((a, b) => a + b);
if (sum === n) {
res.push([...path]);
}
return;
let res = [];
let path = [];
let sum = 0;
const dfs = (path,index) => {
// 剪枝操作
if (sum > n){
return
}
for (let i = start; i <= 9 - (k - l) + 1; i++) {
if (path.length == k) {
if(sum == n){
res.push([...path]);
return
}
}
for (let i = index; i <= 9 - (k-path.length) + 1;i++) {
path.push(i);
backtrack(i + 1);
path.pop();
sum = sum + i;
index += 1;
dfs(path,index);
sum -= i
path.pop()
}
}
let res = [], path = [];
backtrack(1);
return res;
dfs(path,1);
return res
};
```

View File

@ -328,13 +328,11 @@ var lowestCommonAncestor = function(root, p, q) {
}
if(root.val>p.val&&root.val>q.val) {
// 向左子树查询
let left = lowestCommonAncestor(root.left,p,q);
return left !== null&&left;
return root.left = lowestCommonAncestor(root.left,p,q);
}
if(root.val<p.val&&root.val<q.val) {
// 向右子树查询
let right = lowestCommonAncestor(root.right,p,q);
return right !== null&&right;
return root.right = lowestCommonAncestor(root.right,p,q);
}
return root;
};