From d40a15eccca9212f701c4602a514168ab52fecf6 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Wed, 26 Jan 2022 10:40:30 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=88=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E8=BF=AD=E4=BB=A3=E9=81=8D=E5=8E=86.md?= =?UTF-8?q?=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/二叉树的迭代遍历.md | 55 ++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/problems/二叉树的迭代遍历.md b/problems/二叉树的迭代遍历.md index 4cb94cb5..ba38726b 100644 --- a/problems/二叉树的迭代遍历.md +++ b/problems/二叉树的迭代遍历.md @@ -454,6 +454,61 @@ var postorderTraversal = function(root, res = []) { }; ``` +TypeScript: + +```typescript +// 前序遍历(迭代法) +function preorderTraversal(root: TreeNode | null): number[] { + if (root === null) return []; + let res: number[] = []; + let helperStack: TreeNode[] = []; + let curNode: TreeNode = root; + helperStack.push(curNode); + while (helperStack.length > 0) { + curNode = helperStack.pop()!; + res.push(curNode.val); + if (curNode.right !== null) helperStack.push(curNode.right); + if (curNode.left !== null) helperStack.push(curNode.left); + } + return res; +}; + +// 中序遍历(迭代法) +function inorderTraversal(root: TreeNode | null): number[] { + let helperStack: TreeNode[] = []; + let res: number[] = []; + if (root === null) return res; + let curNode: TreeNode | null = root; + while (curNode !== null || helperStack.length > 0) { + if (curNode !== null) { + helperStack.push(curNode); + curNode = curNode.left; + } else { + curNode = helperStack.pop()!; + res.push(curNode.val); + curNode = curNode.right; + } + } + return res; +}; + +// 后序遍历(迭代法) +function postorderTraversal(root: TreeNode | null): number[] { + let helperStack: TreeNode[] = []; + let res: number[] = []; + let curNode: TreeNode; + if (root === null) return res; + helperStack.push(root); + while (helperStack.length > 0) { + curNode = helperStack.pop()!; + res.push(curNode.val); + if (curNode.left !== null) helperStack.push(curNode.left); + if (curNode.right !== null) helperStack.push(curNode.right); + } + return res.reverse(); +}; +``` + Swift: > 迭代法前序遍历