File tree Expand file tree Collapse file tree 1 file changed +42
-1
lines changed Expand file tree Collapse file tree 1 file changed +42
-1
lines changed Original file line number Diff line number Diff line change @@ -265,7 +265,7 @@ func getMinimumDifference(root *TreeNode) int {
265
265
```
266
266
267
267
## JavaScript
268
-
268
+ 递归 先转换为有序数组
269
269
``` javascript
270
270
/**
271
271
* Definition for a binary tree node.
@@ -297,6 +297,47 @@ var getMinimumDifference = function (root) {
297
297
return diff;
298
298
};
299
299
```
300
+ 递归 在递归的过程中更新最小值
301
+ ``` js
302
+ var getMinimumDifference = function (root ) {
303
+ let res = Infinity
304
+ let preNode = null
305
+ // 中序遍历
306
+ const inorder = (node ) => {
307
+ if (! node) return
308
+ inorder (node .left )
309
+ // 更新res
310
+ if (preNode) res = Math .min (res, node .val - preNode .val )
311
+ // 记录前一个节点
312
+ preNode = node
313
+ inorder (node .right )
314
+ }
315
+ inorder (root)
316
+ return res
317
+ }
318
+ ```
319
+
320
+ 迭代 中序遍历
321
+ ``` js
322
+ var getMinimumDifference = function (root ) {
323
+ let stack = []
324
+ let cur = root
325
+ let res = Infinity
326
+ let pre = null
327
+ while (cur || stack .length ) {
328
+ if (cur) {
329
+ stack .push (cur)
330
+ cur = cur .left
331
+ } else {
332
+ cur = stack .pop ()
333
+ if (pre) res = Math .min (res, cur .val - pre .val )
334
+ pre = cur
335
+ cur = cur .right
336
+ }
337
+ }
338
+ return res
339
+ }
340
+ ```
300
341
301
342
-----------------------
302
343
* 作者微信:[ 程序员Carl] ( https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw )
You can’t perform that action at this time.
0 commit comments