File tree Expand file tree Collapse file tree 2 files changed +43
-1
lines changed Expand file tree Collapse file tree 2 files changed +43
-1
lines changed Original file line number Diff line number Diff line change @@ -78,7 +78,7 @@ public:
7878```
7979
8080* 时间复杂度:$O(n^2)$
81- * 空间复杂度:$O(n )$
81+ * 空间复杂度:$O(1 )$
8282
8383C++暴力解法在leetcode上提交也可以过。
8484
Original file line number Diff line number Diff line change @@ -312,5 +312,47 @@ struct TreeNode* convertBST(struct TreeNode* root){
312312}
313313```
314314
315+ ## TypeScript
316+
317+ > 递归法
318+
319+ ```typescript
320+ function convertBST(root: TreeNode | null): TreeNode | null {
321+ let pre: number = 0;
322+ function recur(root: TreeNode | null): void {
323+ if (root === null) return;
324+ recur(root.right);
325+ root.val += pre;
326+ pre = root.val;
327+ recur(root.left);
328+ }
329+ recur(root);
330+ return root;
331+ };
332+ ```
333+
334+ > 迭代法
335+
336+ ``` typescript
337+ function convertBST(root : TreeNode | null ): TreeNode | null {
338+ const helperStack: TreeNode [] = [];
339+ let curNode: TreeNode | null = root ;
340+ let pre: number = 0 ;
341+ while (curNode !== null || helperStack .length > 0 ) {
342+ while (curNode !== null ) {
343+ helperStack .push (curNode );
344+ curNode = curNode .right ;
345+ }
346+ curNode = helperStack .pop ()! ;
347+ curNode .val += pre ;
348+ pre = curNode .val ;
349+ curNode = curNode .left ;
350+ }
351+ return root ;
352+ };
353+ ```
354+
355+
356+
315357-----------------------
316358<div align =" center " ><img src =https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width =500 > </img ></div >
You can’t perform that action at this time.
0 commit comments