From ad24b1fb1fa50e568a7357bbe772df59fc008e74 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Sat, 11 Jun 2022 18:29:48 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880116.=E5=A1=AB?= =?UTF-8?q?=E5=85=85=E6=AF=8F=E4=B8=AA=E8=8A=82=E7=82=B9=E7=9A=84=E4=B8=8B?= =?UTF-8?q?=E4=B8=80=E4=B8=AA=E5=8F=B3=E4=BE=A7=E8=8A=82=E7=82=B9=E6=8C=87?= =?UTF-8?q?=E9=92=88.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...个节点的下一个右侧节点指针.md | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/problems/0116.填充每个节点的下一个右侧节点指针.md b/problems/0116.填充每个节点的下一个右侧节点指针.md index 2c443de5..1e5b2271 100644 --- a/problems/0116.填充每个节点的下一个右侧节点指针.md +++ b/problems/0116.填充每个节点的下一个右侧节点指针.md @@ -287,6 +287,79 @@ const connect = root => { }; ``` +## TypeScript + +(注:命名空间‘Node’与typescript中内置类型冲突,这里改成了‘NodePro’) + +> 递归法: + +```typescript +class NodePro { + val: number + left: NodePro | null + right: NodePro | null + next: NodePro | null + constructor(val?: number, left?: NodePro, right?: NodePro, next?: NodePro) { + this.val = (val === undefined ? 0 : val) + this.left = (left === undefined ? null : left) + this.right = (right === undefined ? null : right) + this.next = (next === undefined ? null : next) + } +} + +function connect(root: NodePro | null): NodePro | null { + if (root === null) return null; + root.next = null; + recur(root); + return root; +}; +function recur(node: NodePro): void { + if (node.left === null || node.right === null) return; + node.left.next = node.right; + node.right.next = node.next && node.next.left; + recur(node.left); + recur(node.right); +} +``` + +> 迭代法: + +```typescript +class NodePro { + val: number + left: NodePro | null + right: NodePro | null + next: NodePro | null + constructor(val?: number, left?: NodePro, right?: NodePro, next?: NodePro) { + this.val = (val === undefined ? 0 : val) + this.left = (left === undefined ? null : left) + this.right = (right === undefined ? null : right) + this.next = (next === undefined ? null : next) + } +} + +function connect(root: NodePro | null): NodePro | null { + if (root === null) return null; + const queue: NodePro[] = []; + queue.push(root); + while (queue.length > 0) { + for (let i = 0, length = queue.length; i < length; i++) { + const curNode: NodePro = queue.shift()!; + if (i === length - 1) { + curNode.next = null; + } else { + curNode.next = queue[0]; + } + if (curNode.left !== null) queue.push(curNode.left); + if (curNode.right !== null) queue.push(curNode.right); + } + } + return root; +}; +``` + + + -----------------------