-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathProblem83.js
More file actions
73 lines (67 loc) · 1.32 KB
/
Problem83.js
File metadata and controls
73 lines (67 loc) · 1.32 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
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^invertTree" }] */
// Problem 83
//
// This problem was asked by Google.
//
// Invert a binary tree.
//
// For example, given the following tree:
//
// a
// / \
// b c
// / \ /
// d e f
// should become:
//
// a
// / \
// c b
// \ / \
// f e d
//
// https://leetcode.com/problems/invert-binary-tree/
//
// O(N) Time complexity
// O(N) Space complexity
// N is the number of nodes in thre tree
/**
* Inverts a binary tree
* @param {TreeNode} root
*/
function invertTree(root) {
// return invertTreeR(root);
return invertTreeI(root);
}
/**
* Recursive invert binary tree
* @param {TreeNode} root
*/
function invertTreeR(root) {
if (root !== null) {
const temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
}
}
/**
* Iterative invert binary tree
* @param {TreeNode} root
*/
function invertTreeI(root) {
if (root !== null) {
const queue = [];
queue.push(root);
while (queue.length !== 0) {
const node = queue.shift();
const temp = node.left;
node.left = node.right;
node.right = temp;
if (node.left !== null) queue.push(node.left);
if (node.right !== null) queue.push(node.right);
}
}
}
export default invertTree;