首页 > 其他 > 详细

LeetCode 116. Populating Next Right Pointers in Each Node

时间:2016-02-18 01:20:47      阅读:146      评论:0      收藏:0      [点我收藏+]

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


ver0:
 1 class Solution {
 2 public:
 3     void connect(TreeLinkNode *root) {
 4         if(root ==  NULL) return;
 5         root->left->next = root->right;//ERROR
 6         if(root->next) root->right->next = root->next->left;
 7         connect(root->left); connect(root->right);
 8         root->next = NULL;
 9     }
10 };

RA:{0} root->left right均为NULL。

 

ver1:28ms

 1 class Solution {
 2 public:
 3     void connect(TreeLinkNode *root) {
 4         if(root ==  NULL) return;
 5         if(root->left && root->right){
 6             root->left->next = root->right;
 7             if(root->next) root->right->next = root->next->left;
 8             connect(root->left); connect(root->right);
 9         }
10         else return;
11     }
12 };

 

ver2:24ms

 1 class Solution {
 2 public:
 3     void connect(TreeLinkNode *root) {
 4         if(root ==  NULL) return;
 5         if(root->left && root->right){
 6             root->left->next = root->right;
 7             if(root->next) root->right->next = root->next->left;
 8             
 9         }
10         connect(root->left); connect(root->right);
11         // else return;
12     }
13 };

 

 

LeetCode 116. Populating Next Right Pointers in Each Node

原文:http://www.cnblogs.com/co0oder/p/5196937.html

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