Populating Next Right Pointers in Each Node I
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 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 -> NULL
Populating Next Right Pointers in Each Node II
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
1 / 2 3 / 4 5 7
After calling your function, the tree should look like:
1 -> NULL / 2 -> 3 -> NULL / 4-> 5 -> 7 -> NULL
这两题差不太多,我是按照第二题的要求来做的,这样第二题的代码也可以AC第一题的,一举两得。
个人思路:
1,很自然想到广度优先遍历,并且当我们要考虑连接第i层结点的next指针时,前i-1层的结点的next指针都已经连接好了,因为在广度优先遍历下,前i-1层的结点是在第i层结点之前就处理过的,如果找到了i-1层结点和第i层结点之间的关系,又第一层结点是根节点,那么就很容易从上到下解决这个问题,假设此时i = 3,则有如下:
1 -> NULL / 2 -> 3 -> NULL / 4 5 7
2,可以设置第i-1层的起始结点指针为preStart = 2,用于遍历第i-1层结点的指针preCur = preStart,同样,设置第i层的起始结点的指针为curStart,用于遍历第i层结点的指针为curCur,初始时curCur = curStart = NULL
3,从preCur开始遍历第i-1层的结点(通过结点的next指针遍历,此时可以将第i-1层的看成一个单链表),每次遍历都查看preCur的左孩子和右孩子,并且根据孩子的存在情况设置curStart指针和curCur指针,直到preCur为NULL,此时表明第i层的结点均处理完毕,重新设置一下这4个指针,用同样的方式处理下一层结点
代码:
1 #include<stddef.h> 2 3 struct TreeLinkNode { 4 int val; 5 TreeLinkNode *left, *right, *next; 6 TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7 }; 8 class Solution { 9 public: 10 void connect(TreeLinkNode *root) { 11 if (nullptr == root) 12 { 13 return; 14 } 15 16 TreeLinkNode *preStart = root; 17 TreeLinkNode *preCur = preStart; 18 TreeLinkNode *curStart = nullptr; 19 TreeLinkNode *curCur = nullptr; 20 21 while (nullptr != preStart) 22 { 23 if (nullptr != preCur->left) 24 { 25 if (nullptr != curStart) 26 { 27 curCur->next = preCur->left; 28 curCur = curCur->next; 29 } 30 else 31 { 32 curCur = curStart = preCur->left; 33 } 34 } 35 36 if (nullptr != preCur->right) 37 { 38 if (nullptr != curStart) 39 { 40 curCur->next = preCur->right; 41 curCur = curCur->next; 42 } 43 else 44 { 45 curCur = curStart = preCur->right; 46 } 47 } 48 49 preCur = preCur->next; 50 51 if (nullptr == preCur) 52 { 53 preCur = preStart = curStart; 54 curCur = curStart = nullptr; 55 } 56 } 57 } 58 };