LeetCode 116. Populating Next Right Pointers in Each Node

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 116. Populating Next Right Pointers in Each Node相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-116-Populating Next Right Pointers in Each Node

leetcode 116. Populating Next Right Pointers in Each Node

leetcode@ [116/117] Populating Next Right Pointers in Each Node I & II (Tree, BFS)

leetcode 116 Populating Next Right Pointers in Each Node ----- java

LeetCode OJ 116. Populating Next Right Pointers in Each Node

Leetcode 116. Populating next right pointers in each node I and II