标签:style blog class code java ext
Populating Next Right Pointers in Each Node
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:
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
先不考虑空间复杂度限制
从图例就可以得到解法,就是层次遍历。
每一层的前一个节点next指向后一个节点,层次之间不相连。
也就是说,
如果当前加入的节点cur是左子结点,那么需要判断一下,该节点是不是新一层的第一个节点。
若是:上一个节点pre的next不需要指向当前节点
若否:上一个节点pre的next需要指向当前节点如果当前加入的节点cur是右子结点,那么不需要判断,上一个节点pre的next需要指向当前节点。
class Solution { public: queue<TreeLinkNode*> q; void connect(TreeLinkNode *root) { if(root == NULL) return; int ind_count = 0; int pow_count = 1; q.push(root); ind_count ++; TreeLinkNode *cur = root; TreeLinkNode *pre = root; TreeLinkNode *temp = root; while(!q.empty()) { temp = q.front(); q.pop(); if(temp->left) { q.push(temp->left); pre = cur; cur = temp->left; ind_count ++; if(ind_count != pow(2.0, pow_count)) { pre->next = cur; } else { pow_count ++; } } if(temp->right) { q.push(temp->right); pre = cur; cur = temp->right; ind_count ++; pre->next = cur; } } } };

接下来我们考虑怎样去掉队列进行层次遍历。
首先我们需要一个指示器,告诉我们每一层的开始,然后在遍历该层的时候将下一层的next进行连接。(遍历依赖于上一层建立好的next)
想法参考Discussion后自己动手实现
class Solution { public: void connect(TreeLinkNode *root) { TreeLinkNode* leftWall = root; TreeLinkNode* cur; while(leftWall != NULL) { cur = leftWall; while(cur != NULL) { if(cur->left != NULL) cur->left->next = cur->right; if(cur->right != NULL && cur->next != NULL) cur->right->next = cur->next->left; cur = cur->next; } leftWall = leftWall->left; } } };

【LeetCode】Populating Next Right Pointers in Each Node,布布扣,bubuko.com
【LeetCode】Populating Next Right Pointers in Each Node
标签:style blog class code java ext
原文地址:http://www.cnblogs.com/ganganloveu/p/3718568.html