-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvert_binary_tree.cpp
More file actions
67 lines (55 loc) · 1.75 KB
/
invert_binary_tree.cpp
File metadata and controls
67 lines (55 loc) · 1.75 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
/*
Problem: Invert Binary Tree
(https://leetcode.com/problems/invert-binary-tree/)
Inverting a binary tree can be done using both BFS and DFS methods.
BFS iteratively inverts nodes on the same level/height at a time, from the root.
DFS recursively inverts the children nodes for each subtree at a time.
Both must traverse through the whole tree, being O(n) time.
BFS uses a queue to keep track of the nodes to "expand," increasing space complexity.
DFS uses recursion, which adds more stack frames, increasing space complexity.
DFS is cleaner and shorter but BFS isn't too complex either.
BFS is probably the optimal choice.
*/
#include <vector>
#include <queue>
#include <iostream>
#include <string>
using namespace std;
//Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//DFS
TreeNode* invertTree(TreeNode* root) {
if (root == NULL) return root;
invertTree(root->left);
invertTree(root->right);
swap(root->left, root->right);
return root;
}
//BFS
TreeNode* invertTree(TreeNode* root) {
if (root == NULL) return root;
int numberOfNodesToTraverse;
queue<TreeNode*> nodesToTraverse;
nodesToTraverse.push(root);
while (nodesToTraverse.size() != 0) {
numberOfNodesToTraverse = nodesToTraverse.size();
for (int i = 0; i < numberOfNodesToTraverse; i++) {
if (nodesToTraverse.front() == NULL) {
nodesToTraverse.pop();
continue;
}
swap(nodesToTraverse.front()->left, nodesToTraverse.front()->right);
nodesToTraverse.push(nodesToTraverse.front()->left);
nodesToTraverse.push(nodesToTraverse.front()->right);
nodesToTraverse.pop();
}
}
return root;
}
int main() {
}