recover-a-tree-from-preorder-traversal 1.0.0
Recover a Tree From Preorder Traversal
Loading...
Searching...
No Matches
Solution Class Reference

Public Member Functions

TreeNoderecoverFromPreorder (string traversal)
 

Detailed Description

Definition at line 15 of file main.cpp.

Member Function Documentation

◆ recoverFromPreorder()

TreeNode * Solution::recoverFromPreorder ( string  traversal)
inline

Definition at line 18 of file main.cpp.

19 {
20 // (node, level)
21 stack<pair<TreeNode*, int>> st;
22 int i = 0;
23
24 // interate through traversal string
25 while (i < (int)traversal.size())
26 {
27 int level = 0;
28
29 // count the dashes to determine current level
30 while (i < (int)traversal.size() && traversal[i] == '-')
31 {
32 level++;
33 i++;
34 }
35
36 int value = 0;
37
38 // parse numeric value of current node
39 while (i < (int)traversal.size() && isdigit(traversal[i]))
40 {
41 value = value * 10 + (traversal[i] - '0');
42 i++;
43 }
44
45 // allocate new node
46 TreeNode* node = new TreeNode(value);
47 while (!st.empty() && st.top().second >= level)
48 st.pop();
49
50 // attach node to proper place using stack
51 if (!st.empty())
52 {
53 if (!st.top().first->left)
54 st.top().first->left = node;
55 else
56 st.top().first->right = node;
57 }
58
59 // push new node to the top of the stack
60 st.push({node, level});
61 }
62
63 // drop all elements of the stack to uncover the root
64 while ((int)st.size() > 1)
65 st.pop();
66 return st.top().first;
67 }
TreeNode * right
Definition main.cpp:9

References TreeNode::right.

Referenced by main().


The documentation for this class was generated from the following file: