diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 5e9fbdfe..df6a3954 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -280,7 +280,7 @@ class Solution: # 返回更新后的以当前root为根节点的新树 return roo -``` +``` **递归法** - 无返回值 ```python @@ -308,7 +308,7 @@ class Solution: return __traverse(root, val) return root -``` +``` **递归法** - 无返回值 - another easier way ```python @@ -378,7 +378,7 @@ func insertIntoBST(root *TreeNode, val int) *TreeNode { } return root } -``` +``` 迭代法 @@ -520,5 +520,71 @@ var insertIntoBST = function (root, val) { }; ``` +## TypeScript + +> 递归-有返回值 + +```typescript +function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null { + if (root === null) return new TreeNode(val); + if (root.val > val) { + root.left = insertIntoBST(root.left, val); + } else { + root.right = insertIntoBST(root.right, val); + } + return root; +}; +``` + +> 递归-无返回值 + +```typescript +function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null { + if (root === null) return new TreeNode(val); + function recur(root: TreeNode | null, val: number) { + if (root === null) { + if (parentNode.val > val) { + parentNode.left = new TreeNode(val); + } else { + parentNode.right = new TreeNode(val); + } + return; + } + parentNode = root; + if (root.val > val) recur(root.left, val); + if (root.val < val) recur(root.right, val); + } + let parentNode: TreeNode = root; + recur(root, val); + return root; +}; +``` + +> 迭代法 + +```typescript +function insertIntoBST(root: TreeNode | null, val: number): TreeNode | null { + if (root === null) return new TreeNode(val); + let curNode: TreeNode | null = root; + let parentNode: TreeNode = root; + while (curNode !== null) { + parentNode = curNode; + if (curNode.val > val) { + curNode = curNode.left + } else { + curNode = curNode.right; + } + } + if (parentNode.val > val) { + parentNode.left = new TreeNode(val); + } else { + parentNode.right = new TreeNode(val); + } + return root; +}; +``` + + + -----------------------