首页 > 其他 > 详细

[LeetCode] Populating Next Right Pointers in Each Node II

时间:2015-07-11 20:00:59      阅读:265      评论:0      收藏:0      [点我收藏+]

The problem becomes more difficult once the binary tree is not perfect. The idea is still similar to use a level-order traversal. Note that we do not need to maintain a queue for the traversal becase the next pointer has provided us with the required information.

The following code is taken from the last answer of this link, which is concise and clean. The use of a dummy node simplifies the code. You may play with the code on some examples to see how it works.

 1 class Solution {
 2 public:
 3     void connect(TreeLinkNode *root) {
 4         TreeLinkNode* dummy = new TreeLinkNode(0);
 5         dummy -> next = root;
 6         while (dummy -> next) {
 7             TreeLinkNode* pre = dummy;
 8             TreeLinkNode* cur = dummy -> next;
 9             pre -> next = NULL;
10             while (cur) {
11                 if (cur -> left) {
12                     pre -> next = cur -> left;
13                     pre = pre -> next;
14                 }
15                 if (cur -> right) {
16                     pre -> next = cur -> right;
17                     pre = pre -> next;
18                 }
19                 cur = cur -> next;
20             }
21         }
22     }
23 };

 

[LeetCode] Populating Next Right Pointers in Each Node II

原文:http://www.cnblogs.com/jcliBlogger/p/4639113.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!