Skip to content

Commit

Permalink
Merge pull request #1022 from taewanseoul/main
Browse files Browse the repository at this point in the history
[Wan] Week 10
  • Loading branch information
SamTheKorean authored Feb 16, 2025
2 parents 2e02d73 + 35dbfd2 commit 86a3ad9
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions invert-binary-tree/taewanseoul.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* 226. Invert Binary Tree
* Given the root of a binary tree, invert the tree, and return its root.
*
* https://leetcode.com/problems/invert-binary-tree/description/
*
*/

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;
}
}

// O(n) time
// O(n) space
function invertTree(root: TreeNode | null): TreeNode | null {
if (!root) {
return null;
}

const left = invertTree(root.left);
const right = invertTree(root.right);

root.left = right;
root.right = left;

return root;
}

0 comments on commit 86a3ad9

Please sign in to comment.