From 826927e6ad0d54dcfd92ff634b7496525b4d2004 Mon Sep 17 00:00:00 2001 From: kok-s0s <2694308562@qq.com> Date: Wed, 23 Jun 2021 22:15:10 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BE=9BJavaScript=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E7=9A=84=E3=80=8A=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91?= =?UTF-8?q?=E4=B8=AD=E7=9A=84=E6=8F=92=E5=85=A5=E6=93=8D=E4=BD=9C=E3=80=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0701.二叉搜索树中的插入操作.md | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 6a8ba7fc..0f5b603a 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -286,6 +286,39 @@ func insertIntoBST(root *TreeNode, val int) *TreeNode { } ``` +JavaScript版本 + +> 有返回值的递归写法 + +```javascript +/** + * Definition for a binary tree node. + * function TreeNode(val, left, right) { + * this.val = (val===undefined ? 0 : val) + * this.left = (left===undefined ? null : left) + * this.right = (right===undefined ? null : right) + * } + */ +/** + * @param {TreeNode} root + * @param {number} val + * @return {TreeNode} + */ +var insertIntoBST = function (root, val) { + const setInOrder = (root, val) => { + if (root === null) { + let node = new TreeNode(val); + return node; + } + if (root.val > val) + root.left = setInOrder(root.left, val); + else if (root.val < val) + root.right = setInOrder(root.right, val); + return root; + } + return setInOrder(root, val); +}; +```