LC117 Populating Next Right Pointers in Each Node II
这道题目关键是先得到上下两层的起始节点,然后分几种情况分别处理:1.下层节点是上层节点的左子节点,且上层节点的右子节点非空。2.下层节点是上层节点的左子节点且上层节点的右子节点为空,或者下层节点是上层节点的右子节点。3.上层节点没有孩子。 分清楚了情况就简单了。
1 class Solution { 2 public: 3 void _connect(TreeLinkNode* root) 4 { 5 TreeLinkNode* tmp = NULL; 6 TreeLinkNode* head = root; 7 while(root!=NULL&&root->left==NULL&&root->right==NULL) 8 root=root->next; 9 if(root==NULL) 10 return; 11 if(root->left!=NULL) 12 tmp=root->left; 13 else 14 tmp=root->right; 15 TreeLinkNode* record=tmp; 16 while(root!=NULL) 17 { 18 if(tmp==root->left&&root->right!=NULL) 19 { 20 tmp->next=root->right; 21 tmp=root->right; 22 root=root->next; 23 } 24 else if((tmp==root->left&&root->right==NULL)||(tmp==root->right)) 25 { 26 root=root->next; 27 } 28 else 29 { 30 if(root->left!=NULL) 31 { 32 tmp->next=root->left; 33 tmp=tmp->next; 34 } 35 else if(root->right!=NULL) 36 { 37 tmp->next=root->right; 38 tmp=tmp->next; 39 root=root->next; 40 } 41 else 42 root=root->next; 43 } 44 } 45 _connect(record); 46 } 47 void connect(TreeLinkNode *root) { 48 if(root==NULL) 49 return; 50 _connect(root); 51 } 52 };