Skip to content

Commit d40a15e

Browse files
committed
添加(二叉树的迭代遍历.md):增加typescript版本
1 parent fec8e08 commit d40a15e

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

problems/二叉树的迭代遍历.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,61 @@ var postorderTraversal = function(root, res = []) {
454454
};
455455
```
456456

457+
TypeScript:
458+
459+
```typescript
460+
// 前序遍历(迭代法)
461+
function preorderTraversal(root: TreeNode | null): number[] {
462+
if (root === null) return [];
463+
let res: number[] = [];
464+
let helperStack: TreeNode[] = [];
465+
let curNode: TreeNode = root;
466+
helperStack.push(curNode);
467+
while (helperStack.length > 0) {
468+
curNode = helperStack.pop()!;
469+
res.push(curNode.val);
470+
if (curNode.right !== null) helperStack.push(curNode.right);
471+
if (curNode.left !== null) helperStack.push(curNode.left);
472+
}
473+
return res;
474+
};
475+
476+
// 中序遍历(迭代法)
477+
function inorderTraversal(root: TreeNode | null): number[] {
478+
let helperStack: TreeNode[] = [];
479+
let res: number[] = [];
480+
if (root === null) return res;
481+
let curNode: TreeNode | null = root;
482+
while (curNode !== null || helperStack.length > 0) {
483+
if (curNode !== null) {
484+
helperStack.push(curNode);
485+
curNode = curNode.left;
486+
} else {
487+
curNode = helperStack.pop()!;
488+
res.push(curNode.val);
489+
curNode = curNode.right;
490+
}
491+
}
492+
return res;
493+
};
494+
495+
// 后序遍历(迭代法)
496+
function postorderTraversal(root: TreeNode | null): number[] {
497+
let helperStack: TreeNode[] = [];
498+
let res: number[] = [];
499+
let curNode: TreeNode;
500+
if (root === null) return res;
501+
helperStack.push(root);
502+
while (helperStack.length > 0) {
503+
curNode = helperStack.pop()!;
504+
res.push(curNode.val);
505+
if (curNode.left !== null) helperStack.push(curNode.left);
506+
if (curNode.right !== null) helperStack.push(curNode.right);
507+
}
508+
return res.reverse();
509+
};
510+
```
511+
457512
Swift:
458513

459514
> 迭代法前序遍历

0 commit comments

Comments
 (0)