forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJeehay28.js
More file actions
91 lines (74 loc) · 2.21 KB
/
Jeehay28.js
File metadata and controls
91 lines (74 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
// ✔️ Recursive Approach
// Time Complexity: O(N), N = Total number of nodes (each node is processed once)
// Space Complexity: O(H), H = Height of the tree (due to recursion stack depth)
var invertTree = function (root) {
if (!root) return null;
[root.left, root.right] = [root.right, root.left];
invertTree(root.left);
invertTree(root.right);
return root;
};
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
// ✔️ Stack → DFS approach
// Time Complexity: O(N), N = Total number of nodes (each node is processed once)
// Space Complexity: O(H), H = Height of the tree (due to recursion stack depth)
// var invertTree = function (root) {
// let stack = [root];
// while (stack.length > 0) {
// const node = stack.pop();
// if (!node) continue;
// [node.left, node.right] = [node.right, node.left];
// stack.push(node.left);
// stack.push(node.right);
// }
// return root;
// };
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
// ✔️ Queue → BFS
// Time Complexity: O(N), N = Total number of nodes (each node is processed once)
// Space Complexity: O(W), W = Maximum width of the tree
// var invertTree = function (root) {
// let queue = [root];
// while (queue.length > 0) {
// const node = queue.shift();
// if (!node) continue;
// [node.left, node.right] = [node.right, node.left];
// queue.push(node.left);
// queue.push(node.right);
// }
// return root;
// };