Apr 20, 2020 at 7:50pm UTC
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public :
TreeNode* bstFromPreorder(vector<int >& preorder) {
int size = preorder.size();
TreeNode root = TreeNode(preorder[0]);
stack<TreeNode*> st;
int v;
TreeNode newNode = TreeNode(-1);
TreeNode* prevNode;
st.push(&root);
for (int i=1;i<size;i++) {
v = preorder[i];
prevNode = st.top();
newNode = TreeNode(v);
while (!st.empty() && prevNode->val<v) {
st.pop();
prevNode = st.top();
}
if (st.empty()) {
root.right = &newNode;
}
if (v<prevNode->val){
prevNode->left = &newNode;
} else {
prevNode->right = &newNode;
}
st.push(&newNode);
}
return &root;
}
};
Runtime Error:
Line 20: Char 37: runtime error: member access within misaligned address 0x000000000002 for type 'TreeNode', which requires 8 byte alignment (__TreeNodeUtils__.cpp)
0x000000000002: note: pointer points here
<memory cannot be printed>
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior __TreeNodeUtils__.cpp:30:37
Last edited on Apr 20, 2020 at 8:12pm UTC
Apr 20, 2020 at 8:16pm UTC
You appear to be not only returning the address of a local object but also pushing the address of another local object into the tree.
And again, you are shit at asking questions! :-)
And sticking your code in a class called Solution is abnormal in C++. That's more of a Java thing, which I assume is where you picked that up.
Last edited on Apr 20, 2020 at 8:17pm UTC
Apr 20, 2020 at 8:30pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public :
TreeNode* bstFromPreorder(vector<int >& preorder) {
}
};
I hv been provided with this template so I cant help @dutch.
Last edited on Apr 20, 2020 at 8:30pm UTC
Apr 20, 2020 at 9:26pm UTC
Well that explains that then. :-)
If you still want some help maybe you could give me a clue about what the program is supposed to do.
Apr 21, 2020 at 5:30am UTC
Cool. I think i have some bug in logic of my code causing segmentation fault