8000 提供JavaScript版本的《二叉搜索树中的插入操作》 · lee4code/leetcode-master@ad1faf8 · GitHub
[go: up one dir, main page]

Skip to content

Commit ad1faf8

Browse files
committed
提供JavaScript版本的《二叉搜索树中的插入操作》
1 parent 826927e commit ad1faf8

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

problems/0701.二叉搜索树中的插入操作.md

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,84 @@ var insertIntoBST = function (root, val) {
320320
};
321321
```
322322

323+
> 无返回值的递归
323324

325+
```javascript
326+
/**
327+
* Definition for a binary tree node.
328+
* function TreeNode(val, left, right) {
329+
* this.val = (val===undefined ? 0 : val)
330+
* this.left = (left===undefined ? null : left)
331+
* this.right = (right===undefined ? null : right)
332+
* }
333+
*/
334+
/**
335+
* @param {TreeNode} root
336+
* @param {number} val
337+
* @return {TreeNode}
338+
*/
339+
var insertIntoBST = function (root, val) {
340+
let parent = new TreeNode(0);
341+
const preOrder = (cur, val) => {
342+
if (cur === null) {
343+
let node = new TreeNode(val);
344+
if (parent.val > val)
345+
parent.left = node;
346+
else
347+
parent.right = node;
348+
return;
349+
}
350+
parent = cur;
351+
if (cur.val > val)
352+
preOrder(cur.left, val);
353+
if (cur.val < val)
354+
preOrder(cur.right, val);
355+
}
356+
if (root === null)
357+
root = new TreeNode(val);
358+
preOrder(root, val);
359+
return root;
360+
};
361+
```
362+
363+
> 迭代
364+
365+
```javascript
366+
/**
367+
* Definition for a binary tree node.
368+
* function TreeNode(val, left, right) {
369+
* this.val = (val===undefined ? 0 : val)
370+
* this.left = (left===undefined ? null : left)
371+
* this.right = (right===undefined ? null : right)
372+
* }
373+
*/
374+
/**
375+
* @param {TreeNode} root
376+
* @param {number} val
377+
* @return {TreeNode}
378+
*/
379+
var insertIntoBST = function (root, val) {
380+
if (root === null) {
381+
root = new TreeNode(val);
382+
} else {
383+
let parent = new TreeNode(0);
384+
let cur = root;
385+
while (cur) {
386+
parent = cur;
387+
if (cur.val > val)
388+
cur = cur.left;
389+
else
390+
cur = cur.right;
391+
}
392+
let node = new TreeNode(val);
393+
if (parent.val > val)
394+
parent.left = node;
395+
else
396+
parent.right = node;
397+
}
398+
return root;
399+
};
400+
```
324401

325402
-----------------------
326403
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)

0 commit comments

Comments
 (0)
0