Skip to content

[gitsunmin] Week 10 Solutions #540

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 19, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions invert-binary-tree/gitsunmin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* https://leetcode.com/problems/invert-binary-tree/
* time complexity : O(n)
* space complexity : O(log N)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dfs를 사용하셨고 T.C. 가 O(n)이라면, 최악의 경우 S.C.또한 O(n)이 되지 않을까요?

*/

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

export const dfs = (root: TreeNode | null, inverted: TreeNode | null): TreeNode | null => {
if (!root) return null;

const left = dfs(root.left, inverted);
const right = dfs(root.right, inverted);

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

return root;
};

function invertTree(root: TreeNode | null): TreeNode | null {
if (!root) return null;

return dfs(root, new TreeNode(0));
};