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 };