mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #1416 from wzqwtt/tree15
添加(0236.二叉树的最近公共祖先、0235.二叉搜索树的最近公共祖先) Scala版本
This commit is contained in:
@ -381,7 +381,36 @@ function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: Tree
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Scala
|
||||||
|
|
||||||
|
递归:
|
||||||
|
|
||||||
|
```scala
|
||||||
|
object Solution {
|
||||||
|
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = {
|
||||||
|
// scala中每个关键字都有其返回值,于是可以不写return
|
||||||
|
if (root.value > p.value && root.value > q.value) lowestCommonAncestor(root.left, p, q)
|
||||||
|
else if (root.value < p.value && root.value < q.value) lowestCommonAncestor(root.right, p, q)
|
||||||
|
else root
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
迭代:
|
||||||
|
|
||||||
|
```scala
|
||||||
|
object Solution {
|
||||||
|
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = {
|
||||||
|
var curNode = root // 因为root是不可变量,所以要赋值给curNode一个可变量
|
||||||
|
while(curNode != null){
|
||||||
|
if(curNode.value > p.value && curNode.value > q.value) curNode = curNode.left
|
||||||
|
else if(curNode.value < p.value && curNode.value < q.value) curNode = curNode.right
|
||||||
|
else return curNode
|
||||||
|
}
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
@ -343,7 +343,25 @@ function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: Tree
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Scala
|
||||||
|
|
||||||
|
```scala
|
||||||
|
object Solution {
|
||||||
|
def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode): TreeNode = {
|
||||||
|
// 递归结束条件
|
||||||
|
if (root == null || root == p || root == q) {
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
|
||||||
|
var left = lowestCommonAncestor(root.left, p, q)
|
||||||
|
var right = lowestCommonAncestor(root.right, p, q)
|
||||||
|
|
||||||
|
if (left != null && right != null) return root
|
||||||
|
if (left == null) return right
|
||||||
|
left
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
<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