Populating Next Right Pointers in Each Node I
Problem Statement (link):
Given a binary tree
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to
Initially, all next pointers are set to
Note:
For example,
Given the following perfect binary tree,
NULL
.Initially, all next pointers are set to
NULL
.Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1 / \ 2 3 / \ / \ 4 5 6 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULLAnalysis:
BFS using queue is an obvious solution to this problem. However, as we are asked to solve it without using extra space, we gotta find another way.
There are two types of connections:
1) Connect a node's left child to its right child;
2) Connect a node's right child to the node's sibling's left child, when the node doesn't have a sibling, we set its right child's next pointer to NULL;
A key is to the solution is that we need to connect the nodes while we are at their parent level, since we couldn't go back to the parent's sibling for type 2) connection.
The following code shows both recursive and iterative approaches.
Code:
Sol 1 - Recursive
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ class Solution { public: void connect(TreeLinkNode *root) { if (!root) return; if (root->left) root->left->next=root->right; if (root->right) root->right->next= root->next ? root->next->left:NULL; connect(root->left); connect(root->right); } };
Sol 2 - Iterative
class Solution { public: void connect(TreeLinkNode *root) { while(root!=NULL) { TreeLinkNode* firstNode=root; while(firstNode!=NULL) { if (firstNode->left) firstNode->left->next=firstNode->right; if (firstNode->right) firstNode->right->next= firstNode->next ? firstNode->next->left:NULL; firstNode=firstNode->next; } root=root->left; } } };
" NagaWorld union members on June 8 submitted a criticism to the Cambodian government in opposition to the on line casino 카지노사이트 operator's plan to fireplace over 1,300 employees
ReplyDelete