Skip to content

Commit 2ffc9a0

Browse files
committed
feat: 226. Invert Binary Tree
1 parent f0389b2 commit 2ffc9a0

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

invert-binary-tree/gwbaik9717.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time complexity: O(n)
2+
// Space complexity: O(n)
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* function TreeNode(val, left, right) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.left = (left===undefined ? null : left)
9+
* this.right = (right===undefined ? null : right)
10+
* }
11+
*/
12+
/**
13+
* @param {TreeNode} root
14+
* @return {TreeNode}
15+
*/
16+
var invertTree = function (root) {
17+
const dfs = (current) => {
18+
if (!current) {
19+
return;
20+
}
21+
22+
const temp = current.left;
23+
current.left = current.right;
24+
current.right = temp;
25+
26+
dfs(current.left);
27+
dfs(current.right);
28+
};
29+
30+
dfs(root);
31+
32+
return root;
33+
};

0 commit comments

Comments
 (0)