Merge pull request #703 from martisss/master

增加530二叉搜索树的最小绝对差.md js递归与迭代解法
This commit is contained in:
程序员Carl
2021-09-04 16:58:43 +08:00
committed by GitHub
2 changed files with 44 additions and 4 deletions

View File

@ -197,11 +197,10 @@ func findContentChildren(g []int, s []int) int {
return child
}
```
Javascript:
```Javascript
```
var findContentChildren = function(g, s) {
g = g.sort((a, b) => a - b)
s = s.sort((a, b) => a - b)

View File

@ -265,7 +265,7 @@ func getMinimumDifference(root *TreeNode) int {
```
## JavaScript
递归 先转换为有序数组
```javascript
/**
* Definition for a binary tree node.
@ -297,6 +297,47 @@ var getMinimumDifference = function (root) {
return diff;
};
```
递归 在递归的过程中更新最小值
```js
var getMinimumDifference = function(root) {
let res = Infinity
let preNode = null
// 中序遍历
const inorder = (node) => {
if(!node) return
inorder(node.left)
// 更新res
if(preNode) res = Math.min(res, node.val - preNode.val)
// 记录前一个节点
preNode = node
inorder(node.right)
}
inorder(root)
return res
}
```
迭代 中序遍历
```js
var getMinimumDifference = function(root) {
let stack = []
let cur = root
let res = Infinity
let pre = null
while(cur || stack.length) {
if(cur) {
stack.push(cur)
cur = cur.left
} else {
cur = stack.pop()
if(pre) res = Math.min(res, cur.val - pre.val)
pre = cur
cur = cur.right
}
}
return res
}
```
-----------------------
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)