You have a binary tree with each node having 3 pointers (left, right, side). Set the side pointers of the last level of the tree to point to their nearby node
/*
You have a binary tree with each node having 3 pointers (left, right, side). Set the side pointers
of the last level of the tree to point to their nearby node
*/
struct TreeNode {
int val;
TreeNode *left, *right, *side;
};
int get_max_height(TreeNode *root) {
if(!root) return 0;
if(!root->left && !root->right) return 1;
int HL = get_max_height(root->left), HR = get_max_height(root->right);
return HL > HR ? HL + 1 : HR + 1;
}
void set_side_pointer(TreeNode *root) {
if(!root) return;
deque<TreeNode*> q;
q.push_back(root);
int max_height = get_max_height(root);
int level1 = 1, level2 = 0, curr_height = 1;
vector<TreeNode*> leaves;
while(!q.empty()) {
TreeNode *cur = q.front();
q.pop_front();
if(curr_height == max_height) {
leaves.push_back(cur);
}
level1--;
if(cur->left) {
q.push_back(cur->left);
level2++;
}
if(cur->right) {
q.push_back(cur->right);
level2++;
}
if(level1 == 0) {
curr_height++;
level1 = level2;
level2 = 0;
}
}
for(int i=0; i<leaves.size()-1; ++i)
leaves[i]->side = leaves[i+1];
}
int main()
{
TreeNode *r = new TreeNode(3);
r->left = new TreeNode(2); r->right = new TreeNode(4);
r->left->left = new TreeNode(1); r->right->right = new TreeNode(5);
set_side_pointer(r);
cout << r->left->left->side->val << endl;
}