Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1130 from xiaofei-2020/tree29
Browse files Browse the repository at this point in the history
添加(0235.二叉搜索树的最近公共祖先.md):增加typescript版本
  • Loading branch information
youngyangyang04 committed Mar 20, 2022
2 parents f2f740f + 246bbe9 commit ceed453
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions problems/0235.二叉搜索树的最近公共祖先.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,39 @@ var lowestCommonAncestor = function(root, p, q) {
};
```

## TypeScript

> 递归法:

```typescript
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
if (root.val > p.val && root.val > q.val)
return lowestCommonAncestor(root.left, p, q);
if (root.val < p.val && root.val < q.val)
return lowestCommonAncestor(root.right, p, q);
return root;
};
```
> 迭代法:
```typescript
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
while (root !== null) {
if (root.val > p.val && root.val > q.val) {
root = root.left;
} else if (root.val < p.val && root.val < q.val) {
root = root.right;
} else {
return root;
};
};
return null;
};
```




-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>

0 comments on commit ceed453

Please sign in to comment.