Skip to content

Commit eb67f6d

Browse files
committed
Feat: 226. Invert Binary Tree
1 parent b6f9956 commit eb67f6d

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

invert-binary-tree/HC-kang.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// class TreeNode {
2+
// val: number;
3+
// left: TreeNode | null;
4+
// right: TreeNode | null;
5+
// constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
6+
// this.val = val === undefined ? 0 : val;
7+
// this.left = left === undefined ? null : left;
8+
// this.right = right === undefined ? null : right;
9+
// }
10+
// }
11+
12+
/**
13+
* https://leetcode.com/problems/invert-binary-tree
14+
* T.C. O(n)
15+
* S.C. O(n)
16+
*/
17+
function invertTree(root: TreeNode | null): TreeNode | null {
18+
if (root === null) {
19+
return null;
20+
}
21+
22+
[root.left, root.right] = [root.right, root.left];
23+
invertTree(root.left);
24+
invertTree(root.right);
25+
26+
return root;
27+
}
28+
29+
/**
30+
* T.C. O(n)
31+
* S.C. O(n)
32+
*/
33+
function invertTree(root: TreeNode | null): TreeNode | null {
34+
const stack: Array<TreeNode | null> = [root];
35+
36+
while (stack.length > 0) {
37+
const node = stack.pop()!;
38+
39+
if (node === null) {
40+
continue;
41+
}
42+
43+
[node.left, node.right] = [node.right, node.left];
44+
stack.push(node.left, node.right);
45+
}
46+
47+
return root;
48+
}

0 commit comments

Comments
 (0)