码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 116. Populating Next Right Pointers in Each Node

时间:2016-02-18 01:21:18      阅读:219      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!