首页 > 代码库 > LeetCode--Populating Next Right Pointers in Each Node II

LeetCode--Populating Next Right Pointers in Each Node II

同上题:

但是这题需要考虑好对当前节点的left和right的next指针如何设置。

 1 /** 2  * Definition for binary tree with next pointer. 3  * struct TreeLinkNode { 4  *  int val; 5  *  TreeLinkNode *left, *right, *next; 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7  * }; 8  */ 9 class Solution {10 public:11     void connect(TreeLinkNode *root) {12         if(root == NULL){13             return;14         }15         TreeLinkNode *leftNext = NULL;16         TreeLinkNode *rightNext = NULL;17         TreeLinkNode *node = NULL;18         if(root->left){19             leftNext = root->right;20             node = root->next;21             while(!leftNext && node){22                 if(node->left){23                     leftNext = node->left;24                     break;25                 }26                 if(node->right){27                     leftNext = node->right;28                     break;29                 }30                 node = node->next;31             }32             root->left->next = leftNext;33         }34         if(root->right){35             rightNext = NULL;36             node = root->next;37             while(!rightNext && node){38                 if(node->left){39                     rightNext = node->left;40                     break;41                 }42                 if(node->right){43                     rightNext = node->right;44                     break;45                 }46                 node = node->next;47             }48             root->right->next = rightNext;49         }50         connect(root->right);51         connect(root->left);52     }53 };

root->left和root->right顺序不能变。

LeetCode--Populating Next Right Pointers in Each Node II