-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinvert_binary_tree.cpp
More file actions
68 lines (47 loc) · 1.36 KB
/
invert_binary_tree.cpp
File metadata and controls
68 lines (47 loc) · 1.36 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
// Copyright (c) Omar Boukli-Hacene. All rights reserved.
// Distributed under an MIT-style license that can be
// found in the LICENSE file.
// SPDX-License-Identifier: MIT
#include "forfun/graph/invert_binary_tree.hpp"
#include <deque>
#include <utility>
#include "forfun/graph/binary_tree_node.hpp"
namespace forfun::graph::invert_binary_tree {
namespace iterative {
auto invert_binary_tree(binary_tree_node& root) -> void
{
using std::swap;
std::deque<binary_tree_node*> tracker{};
tracker.push_back(&root);
while (not tracker.empty())
{
binary_tree_node* node{tracker.front()};
tracker.pop_front();
swap(node->left_node_, node->right_node_);
if (node->left_node_ != nullptr)
{
tracker.push_back(node->left_node_);
}
if (node->right_node_ != nullptr)
{
tracker.push_back(node->right_node_);
}
}
}
} // namespace iterative
namespace recursive {
auto invert_binary_tree(binary_tree_node& root) noexcept -> void
{
using std::swap;
swap(root.left_node_, root.right_node_);
if (root.left_node_ != nullptr)
{
invert_binary_tree(*root.left_node_);
}
if (root.right_node_ != nullptr)
{
invert_binary_tree(*root.right_node_);
}
}
} // namespace recursive
} // namespace forfun::graph::invert_binary_tree