mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加(0235.二叉搜索树的最近公共祖先.md):增加typescript版本
This commit is contained in:
@ -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>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user