Skip to content

Commit 86a3ad9

Browse files
authored
Merge pull request #1022 from taewanseoul/main
[Wan] Week 10
2 parents 2e02d73 + 35dbfd2 commit 86a3ad9

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

invert-binary-tree/taewanseoul.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* 226. Invert Binary Tree
3+
* Given the root of a binary tree, invert the tree, and return its root.
4+
*
5+
* https://leetcode.com/problems/invert-binary-tree/description/
6+
*
7+
*/
8+
9+
class TreeNode {
10+
val: number;
11+
left: TreeNode | null;
12+
right: TreeNode | null;
13+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
14+
this.val = val === undefined ? 0 : val;
15+
this.left = left === undefined ? null : left;
16+
this.right = right === undefined ? null : right;
17+
}
18+
}
19+
20+
// O(n) time
21+
// O(n) space
22+
function invertTree(root: TreeNode | null): TreeNode | null {
23+
if (!root) {
24+
return null;
25+
}
26+
27+
const left = invertTree(root.left);
28+
const right = invertTree(root.right);
29+
30+
root.left = right;
31+
root.right = left;
32+
33+
return root;
34+
}

0 commit comments

Comments
 (0)