Merge pull request #1416 from wzqwtt/tree15

添加(0236.二叉树的最近公共祖先、0235.二叉搜索树的最近公共祖先) Scala版本
This commit is contained in:
程序员Carl
2022-07-04 09:04:34 +08:00
committed by GitHub
2 changed files with 47 additions and 0 deletions

View File

@ -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
}
}
```
-----------------------

View File

@ -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>