forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHC-kang.ts
More file actions
48 lines (40 loc) · 1.01 KB
/
HC-kang.ts
File metadata and controls
48 lines (40 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// class TreeNode {
// val: number;
// left: TreeNode | null;
// right: TreeNode | null;
// constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
// this.val = val === undefined ? 0 : val;
// this.left = left === undefined ? null : left;
// this.right = right === undefined ? null : right;
// }
// }
/**
* https://leetcode.com/problems/invert-binary-tree
* T.C. O(n)
* S.C. O(n)
*/
function invertTree(root: TreeNode | null): TreeNode | null {
if (root === null) {
return null;
}
[root.left, root.right] = [root.right, root.left];
invertTree(root.left);
invertTree(root.right);
return root;
}
/**
* T.C. O(n)
* S.C. O(n)
*/
function invertTree(root: TreeNode | null): TreeNode | null {
const stack: Array<TreeNode | null> = [root];
while (stack.length > 0) {
const node = stack.pop()!;
if (node === null) {
continue;
}
[node.left, node.right] = [node.right, node.left];
stack.push(node.left, node.right);
}
return root;
}