mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加(二叉树的迭代遍历.md):增加typescript版本
This commit is contained in:
@ -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:
|
||||
|
||||
> 迭代法前序遍历
|
||||
|
Reference in New Issue
Block a user