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
|
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <stack>
using std::vector;
using std::stack;
using std::cout;
//Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
~TreeNode() {
cout << "TreeNode.dtor[val=" << val << "] called!\n";
}
};
struct Tree {
vector<TreeNode*> tree;
// treeVals should be a valid array-representation of a binary tree
Tree(const vector<int> treeVals) {
if (treeVals.empty()) return;
for (auto val : treeVals) tree.push_back(new TreeNode(val));
// Set up the tree structure
for (unsigned int i = 1; i < treeVals.size(); ++i) {
if (i % 2 == 1) {
tree[(i - 1) / 2]->left = tree[i];
}
else {
tree[(i - 1) / 2]->right = tree[i];
}
}
}
~Tree() {
for (auto tn : tree) delete tn;
}
};
class Solution {
public:
static vector<int> preorderTraversal(TreeNode* root) {
if (!root) return vector<int>{};
vector<int> visited;
stack<TreeNode*> stk; // stk: Stores nodes to be visited; top node is the next node to visit
stk.push(root); // Initialize the stack with root node
while (!stk.empty()) {
auto node = stk.top();
visited.push_back(node->val); // "Visit" the node
stk.pop();
// If children nodes exists, mark them for visitation
if (node->right) stk.push(node->right);
if (node->left) stk.push(node->left); // Left child must be top element for preorder traversal.
}
return visited;
}
};
int main()
{
// Picture of tree can be found here: https://en.wikipedia.org/wiki/Heap_(data_structure)
Tree t1(vector<int>{100, 19, 36, 17, 3, 25, 1, 2, 7});
for (auto val : Solution::preorderTraversal(t1.tree[0])) cout << val << ",";
cout << "\n Exiting ...\n";
return 0;
}
|